Python 標準ライブラリ sqlite3 SQLiteデータベース
Publish date: 2021-08-06
ライブラリsqlite3を使うとPythonでデータベースSQLiteを利用することができる。
SQLiteのデータベース作成・挿入・使用例
contextlibモジュールのclosingを使うとsqlite3のコネクションを withを使って自動で閉じられるようになる。
import sqlite3
from contextlib import closing
with closing(sqlite3.connect('sample.db')) as con:
cursor = con.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS person
(name TEXT, age INTEGER, departmnet TEXT)
""")
cursor.execute("DELETE FROM person ;")
cursor.execute("INSERT INTO person VALUES ('Taro', 25, 'A1' );")
cursor.execute("INSERT INTO person VALUES ('Jiro', 20, 'B1' );")
cursor.execute("INSERT INTO person VALUES ('Hanako', 22, 'A2' );")
con.commit()
cursor.execute("SELECT name, age, departmnet FROM person;")
print(cursor.fetchall())
# => [('Taro', 25, 'A1'), ('Jiro', 20, 'B1'), ('Hanako', 22, 'A2')]
for person in cursor.execute("SELECT name, age, departmnet FROM person;"):
print(person)
# ('Taro', 25, 'A1')
# ('Jiro', 20, 'B1')
# ('Hanako', 22, 'A2')
con.close()
executemanyを使うと複数SQLの実行を一度にできる。
with closing(sqlite3.connect(':memory:')) as con:
cursor = con.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS person
(name TEXT, age INTEGER, departmnet TEXT)
""")
cursor.execute("DELETE FROM person ;")
date_list = [
('Taro', 25, 'A1'),
('Jiro', 20, 'B1' ),
('Hanako', 22, 'A2' ),
]
cursor.executemany("INSERT INTO person VALUES (? , ? , ? );", date_list)
con.commit()
params = {'age':20}
cursor.execute("SELECT * FROM person WHERE age >:age ;", params)
print(cursor.fetchall())
# => [('Taro', 25, 'A1'), ('Hanako', 22, 'A2')]
con.close()
「con.row_factory = sqlite3.Row」と指定することで、 cursor.executeの実行結果の使用の際、列名でのアクセスができるようになる。
with closing(sqlite3.connect(':memory:')) as con:
con.row_factory = sqlite3.Row
cursor = con.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS person
(name TEXT, age INTEGER, departmnet TEXT)
""")
cursor.execute("DELETE FROM person ;")
date_list = [
('Taro', 25, 'A1'),
('Jiro', 20, 'B1' ),
('Hanako', 22, 'A2' ),
]
cursor.executemany("INSERT INTO person VALUES (? , ? , ? );", date_list)
con.commit()
for person in cursor.execute("SELECT name, age, departmnet FROM person;"):
print(person['name'])
# 'Taro' 'Jiro' 'Hanako'
con.close()