16
22

More than 3 years have passed since last update.

python postgreSQLのライブラリpsycopg2の使い方メモ

Last updated at Posted at 2019-04-12

psycopg2を使うことに決めた理由について

・高速である(ネット情報)
・select結果を辞書形式で取得できる ★これにつきる

psycopg2のselectの仕方(自分がしっくりくる基本はこれ)

※psycopb2をインストールしてから

#import
import psycopg2 
import psycopg2.extras
import os

#postgreSQLに接続(接続情報は環境変数、PG_XXX)
connection = psycopg2.connect(\ 
    host=os.environ.get('PG_HOST'),\ 
    user=os.environ.get('PG_USER'),\ 
    password=os.environ.get('PG_PASS'),\ 
    database=os.environ.get('PG_DBNM'),\ 
    port=int(os.environ.get('PG_PORT'))) 

#クライアントプログラムのエンコードを設定(DBの文字コードから自動変換してくれる)
connection.set_client_encoding('utf-8') 

#select結果を辞書形式で取得するように設定 
connection.cursor_factory=psycopg2.extras.DictCursor

#カーソルの取得
cursor = connection.cursor() 

#SQL文設定(%はバインド変数)
sql = 'select name, work from m_user where id = %(target_id)s'

#SQL実行
target_id = 1
cursor.execute(sql, {'target_id': (target_id,)}) 

#取得結果を出力 ★辞書形式 row['name'] 辞書形式でなければ、row[0]、orz
results = cursor.fetchall() 
for row in results: 
    print(row['name'])
    print(row['work'])

#カーソルをとじる
cursor.close() 

#切断
connection.close() 

参考

・psycopg2のBasic module usage
 http://initd.org/psycopg/docs/usage.html
 ※バインド変数は、「Passing parameters to SQL queries」に記載あり

・psycopg2のThe connection class
 http://initd.org/psycopg/docs/connection.html

・psycopg2のThe cursor class
 http://initd.org/psycopg/docs/cursor.html

・バインドin句の例
 sql = """
select name, work from m_user_a where id in %s
union all
select name, work from m_user_b where id in %s
"""
cursor.execute(sql,(('1', '3', '5'), ('1', '4', '5')))

16
22
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
22