ablog

不器用で落着きのない技術者のメモ

psycopg2 で Pyhton から PostgreSQL に接続する

インストール

$ sudo yum -y install gcc
$ sudo yum -y install postgresql-contrib
$ sudo yum -y install postgresql-devel
$ sudo pip install psycopg2
$ sudo pip install psycopg2-binary

サンプルコード

  • psycopg2_sample.py
import psycopg2
conn = psycopg2.connect("host=aurora-postgres-r42xl.******.ap-northeast-1.rds.amazonaws.com user=awsuser dbname=mydb  port=5432 password=******")
cur = conn.cursor()
cur.execute("DROP TABLE test;")
cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (100, "abc'def"))
cur.execute("SELECT * FROM test;")
row = cur.fetchone()
print(row)
conn.commit()
cur.close()
conn.close()

実行結果

$ python psycopg2_sample.py
(1, 100, "abc'def")

補足

$ python psycopg2_sample.py
/usr/local/lib64/python2.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
  """)

と怒られたので、

$ sudo pip install psycopg2-binary

psycopg2-binary をインストールした。