31
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python psycopg2 で dict形式で結果を取得する

Last updated at Posted at 2016-04-18

Python で HerokuアプリケーションのDB(Postgresql) に接続する実装の中、
結果が配列で取得されてしまいキー値が判別できないことがデバッグ上すごく面倒だった。

調べてみたら下記の解答がいい感じ

get_dict_resultset.py
#!/var/bin/python 
import psycopg2
import psycopg2.extras

def get_dict_resultset(sql):
    conn = psycopg2.connect("dbname=pem host=localhost user=postgres password=Drupal#1008")
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute (sql)
    results = cur.fetchall()
    dict_result = []
    for row in results:
        dict_result.append(dict(row))
    return dict_result

sql = """select * from tablename"""
return get_dict_resultset(sql)

この関数を使えば割りと楽に dict 形式のSQL実行結果が取得できる。

31
28
2

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
31
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?