まずは軽量データベースであるSQLiteの接続方法から解説します。単一ファイルでデータベースを構成し、アプリケーションに組み込んで使用出来るという特性から非常にお手軽です。
ドライバのインストール
Pythonではバージョン2.5よりSQLite関連のライブラリが標準でついています。ドライバのダウンロードは必要ありません。
insertサンプル
データ登録は次のように行います。
import sqlite3
connector = sqlite3.connect('sqlite_test.db')
sql = "insert into test_table values('1', 'python')"
connector.execute(sql)
sql = "insert into test_table values('2', 'パイソン')"
connector.execute(sql)
sql = "insert into test_table values('3', 'ぱいそん')"
connector.execute(sql)
connector.commit()
connector.close()
まずは1行目でsqlite3モジュールのインポートを行います。続く3行目の記述でデータベースへ接続していますが、引数のファイルが存在しない場合は自動的に作成されます。5行目から10行目で指定のSQL文を実行し、12行目でコミットを行っています。最後はデータベース接続を閉じて終了です。
selectサンプル
データ参照は次のように行います。先程登録したデータを見てみましょう。
import sqlite3
connector = sqlite3.connect('sqlite_test.db')
cursor = connector.cursor()
cursor.execute('select * from test_table order by code')
result = cursor.fetchall()
for row in result:
print('===== Hit! =====')
print('code -- ' + row[0])
print('name -- ' + row[1])
cursor.close()
connector.close()
===== Hit! ===== code -- 1 name -- python ===== Hit! ===== code -- 2 name -- パイソン ===== Hit! ===== code -- 3 name -- ぱいそん
sqlite3モジュールのインポート後、データベースへ接続します。4行目でカーソルの取得を行いselect文を実行、fetchallを使用すると結果がタプルで返ってきます。
