2
4

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】PyGreSQLでPostgreSQLに接続する

Posted at

はじめに

PythonでPostgreSQLにアクセスするライブラリといえばpsycopg2(LGPLライセンス)ですが、PyGreSQLというBSDライクなライセンスのライブラリもあります。
というわけで使ってみました。

動作確認はWindows 10、Python 3.6.3、PostgreSQL 9.6.7、PyGreSQL 5.0.4で行いました。

PyGreSQLのインストール

PostgreSQLをインストールします。
libpq.dllへのPATHを通します。

PyGreSQLはpipでインストールします。

pip install PyGreSQL

接続とSQL発行

接続

DBインスタンスを生成することでコネクションを張ります。

In [1]: from pg import DB

In [2]: db = DB(dbname='pygrestest', host='localhost', port=5433, user='postgres', passwd='postgres')

テーブル作成、行の挿入

In [3]: db.query('CREATE TABLE persons(id SERIAL, name TEXT, age INTEGER)')

In [4]: db.query("INSERT INTO persons(name, age) VALUES('John', 33)")
Out[4]: '1'

INSERT文を発行したときは、挿入された行数が返されます。

SELECT文の発行

SELECT文を発行すると、クエリオブジェクトが返されるので、それをprintに渡すと、psqlライクな出力が得られます。

In [5]: q = db.query('SELECT * FROM persons')

In [6]: print(q)
id|name|age
--+----+---
 1|John| 33
(1 row)

クエリオブジェクトのgetresult()を呼び出すとタプルのリスト、dictresult()を呼び出すとディクショナリのリストで結果セットを取得できます。

In [7]: q.getresult()
Out[7]: [(1, 'John', 33)]

In [8]: q.dictresult()
Out[8]: [{'age': 33, 'id': 1, 'name': 'John'}]

処理が終わったら、コネクションを閉じます

In [9]: db.close()

DB-API 2.0インタフェースでの接続

PythonのRDBMSへのアクセスインタフェース規格であるDB-API 2.0に準拠したインタフェースもあります。

In [1]: from pgdb import connect

In [2]: con = connect(database='pygrestest', host='localhost:5433', user='postgres', password='postgres')

In [3]: cursor = con.cursor()

In [4]: cursor.execute("CREATE TABLE languages(id SERIAL, name TEXT)")
Out[4]: <pgdb.Cursor at 0x18452d93438>

In [5]: cursor.execute("INSERT INTO languages(name) VALUES ('Python'), ('C#')")
Out[5]: <pgdb.Cursor at 0x18452d93438>

In [6]: con.commit()

DB-API 2.0は明示的にコミットを呼び出す必要があります。
SELECT文を発行して結果セットを取得するには以下のようにします。

In [7]: cursor.execute('SELECT * FROM languages');

In [8]: rs = cursor.fetchall();

In [9]: rs
Out[9]: [Row(id=1, name='Python'), Row(id=2, name='C#')]

まとめ

PostgreSQLへアクセスするPythonのライブラリとして、PyGreSQLというBSDライクなライセンスなライブラリがあります。
このライブラリは、PyGreSQL独自のインタフェースの他に、DB-API 2.0インタフェースもサポートしています。

2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?