Python SQLite3 モジュール
sqlite3 モジュールを使うと、別のデータベースサーバーなしで Python から直接 SQLite データベースを利用できます。
import sqlite3
SQLite は、小さなアプリ、ローカルツール、テスト、SQL の学習に向いています。データベースは 1 つのファイルに置くことも、':memory:' でメモリ上だけに持つこともできます。
データベースに接続する
SQLite は、存在しない場合にデータベースファイルを自動で作成できます。
import sqlite3
connection = sqlite3.connect(':memory:')
print(type(connection).__name__)
Connection
テーブルを作成して行を挿入する
import sqlite3
connection = sqlite3.connect(':memory:')
cursor = connection.cursor()
cursor.execute('CREATE TABLE users (name TEXT, age INTEGER)')
cursor.execute('INSERT INTO users VALUES (?, ?)', ('Ada', 36))
cursor.execute('INSERT INTO users VALUES (?, ?)', ('Grace', 40))
connection.commit()
SQL 文字列を手で組み立てる代わりに、プレースホルダーを使ってください。
WARNING
ユーザー入力を連結して SQL クエリを作らないでください。SQL インジェクションを避けるため、? のようなプレースホルダーを使います。
行を問い合わせる
rows = cursor.execute('SELECT name, age FROM users ORDER BY age').fetchall()
print(rows)
[('Ada', 36), ('Grace', 40)]
Row オブジェクトを使う
Row を使うと、列名でアクセスできます。
connection = sqlite3.connect(':memory:')
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.execute('CREATE TABLE projects (name TEXT)')
cursor.execute('INSERT INTO projects VALUES (?)', ('python-cheatsheet',))
row = cursor.execute('SELECT name FROM projects').fetchone()
print(row['name'])
python-cheatsheet
コンテキストマネージャーを使う
接続は with と一緒に使えます。エラーがなければ変更は自動で確定されます。
import sqlite3
with sqlite3.connect(':memory:') as connection:
connection.execute('CREATE TABLE notes (body TEXT)')
connection.execute('INSERT INTO notes VALUES (?)', ('Learn sqlite3',))
rows = connection.execute('SELECT body FROM notes').fetchall()
print(rows)
[('Learn sqlite3',)]