PostgreSQL
SQLiteとは違い、いわゆる「本格的」なデータベースの一つであるPostgreSQLのサンプルです。 Pythonに対応したPostgreSQLドライバは数種類ありますが、今回はその中から「psycopg2」を使用します。
ドライバ「psycopg2」は下記リンクよりダウンロードしてください。適切なバージョンとプラットフォームを選びましょう。
http://initd.org/psycopg/download/
ダウンロード後、インストールを行ってください。
データ登録のサンプルとなります。
# -*- coding: utf-8 -*-
import psycopg2
connector = psycopg2.connect(host="localhost", database="pdb", user="pgusr", password="pgpsw")
cursor = connector.cursor()
sql = "insert into test_table values('1', 'python')"
cursor.execute(sql)
sql = "insert into test_table values('2', 'パイソン')"
cursor.execute(sql)
sql = "insert into test_table values('3', 'ぱいそん')"
cursor.execute(sql)
connector.commit()
cursor.close()
connector.close()
3行目で「psycopg2」モジュールのインポートを行います。 続く5行目の記述でデータベースへ接続、引数には(ホスト名, データベース名, ユーザー名, ユーザーのパスワード)を設定します。 6行目でカーソルを取得し、8行目から13行目で指定のSQL文を実行します。 15行目でコミットを行い、最後はデータベースをクローズして終了です。
データ参照のサンプルです。先程登録したデータを見てみましょう。
# -*- coding: utf-8 -*-
import psycopg2
connector = psycopg2.connect(host="localhost", database="pdb", user="pgusr", password="pgpsw")
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 -- ぱいそん
「psycopg2」モジュールのインポート後、データベースへ接続します。 6行目でカーソルの取得を行い、select文を実行。「fetchall」を使用すると結果がタプルで返ってきます。
次はMySQL!
▶外部ライブラリ:MySQL
