SQLite
まずは軽量データベースであるSQLiteの接続方法から解説します。 単一ファイルでデータベースを構成し、アプリケーションに組み込んで使用出来るという特性から非常にお手軽です。
Pythonではバージョン2.5よりSQLite関連のライブラリが標準でついています。 ドライバのダウンロードは必要ありません。
下記データ登録のサンプルとなります。
# -*- coding: utf-8 -*-
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()
まずは3行目で「sqlite3」モジュールのインポートを行います。 続く5行目の記述でデータベースへ接続していますが、引数のファイルが存在しない場合は自動的に作成されます。 7行目から12行目で指定のSQL文を実行し、14行目でコミットを行っています。最後はクローズ処理を行いましょう。
データ参照のサンプルです。先程登録したデータを見てみましょう。
# -*- coding: utf-8 -*-
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 -- " + unicode(row[0])
print "name -- " + unicode(row[1])
cursor.close()
connector.close()
--実行結果--
===== Hit! ===== code -- 1 name -- python ===== Hit! ===== code -- 2 name -- パイソン ===== Hit! ===== code -- 3 name -- ぱいそん
「sqlite3」モジュールのインポート後、データベースへ接続します。 6行目でカーソルの取得を行い、select文を実行。「fetchall」を使用すると結果がタプルで返ってきます。
次はPostgreSQL!
▶外部ライブラリ:PostgreSQL
