LoginSignup
10
15

More than 5 years have passed since last update.

Python から PostgreSQL へ接続

Last updated at Posted at 2018-07-10

install

pip install psycopg2
pip install psycopg2-binary

Running the test suite

python -c "from psycopg2 import tests; tests.unittest.main(defaultTest='tests.test_suite')" --verbose

下記の通りテスト用のDBをあらかじめ準備してあげることによって、実行できるようでした。
createdb -E utf8 psycopg2_test

Basic module usage

あらかじめテスト用DBを作成し

createdb -E utf8 test
python

Pythonのインタラクティブ・モードを起動します。


import psycopg2
conn = psycopg2.connect("dbname=test user=postgres")
cur = conn.cursor()
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;")
cur.fetchone()
conn.commit()
cur.close()
conn.close()

テーブル作成(CREATE)、
データ作成(INSERT)、
データの参照(SELECT)、
まで確認することができました。

参考

Psycopg – PostgreSQL database adapter for Python

10
15
0

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
10
15