1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【初学者向け】Pythonで簡単なCRUD処理を作ってみた

Last updated at Posted at 2022-12-17

はじめに

CRUD(Create, Read, Update, Delete)とは、データベースやWebアプリケーションで扱われる基本的な操作のことを指します。

コード

import sqlite3

# データベースに接続
conn = sqlite3.connect('database.db')

# テーブルを作成
conn.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')

# データを作成(Create)
def create_user(name, email):
    conn.execute("INSERT INTO users (name, email) VALUES (?, ?)", (name, email))
    conn.commit()

# データを読み取り(Read)
def get_user(user_id):
    cursor = conn.execute("SELECT * FROM users WHERE id=?", (user_id,))
    return cursor.fetchone()

# データを更新(Update)
def update_user(user_id, name, email):
    conn.execute("UPDATE users SET name=?, email=? WHERE id=?", (name, email, user_id))
    conn.commit()

# データを削除(Delete)
def delete_user(user_id):
    conn.execute("DELETE FROM users WHERE id=?", (user_id,))
    conn.commit()

# データベースとの接続を閉じる
conn.close()
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?