SQLiteとは違い、いわゆる本格的なデータベースの一つであるPostgreSQLの例です。Pythonに対応したPostgreSQLドライバは数種類ありますが、本サイトではpsycopg2を使用します。
ドライバのインストール
下記コマンドを入力しpsycopg2をインストールしてください。
※これはpipがインストールされていることを前提としています。インストールしていない場合はpipの使い方とインストールを参照してください。
pip install psycopg2
insertサンプル
データ登録は次のように行います。
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()
1行目でpsycopg2モジュールのインポートを行います。続く3行目から8行目の記述でデータベースへ接続、引数には(ホスト名, データベース名, ユーザー名, ユーザーのパスワード)を設定します。9行目でカーソルを取得し、11行目から16行目で指定のSQL文を実行します。18行目でコミットを行い、最後はデータベース接続を閉じて終了です。
selectサンプル
データ参照は次のように行います。先程登録したデータを見てみましょう。
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 -- ' + row[0])
print('name -- ' + row[1])
cursor.close()
connector.close()
===== Hit! ===== code -- 1 name -- python ===== Hit! ===== code -- 2 name -- パイソン ===== Hit! ===== code -- 3 name -- ぱいそん
psycopg2モジュールのインポート後、データベースへ接続します。9行目でカーソルの取得を行いselect文を実行、fetchallを使用すると結果がタプルで返ってきます。
