[Python][WSL] Python から PostgreSQL を操作する

  • 2022年9月18日
  • 2022年9月18日
  • Python
  • 200View
  • 0件

はじめに

PostgreSQL は、SQL準拠のオープンソースの RDBMS です。
stackoverflow survey の Database ランキングで Loved の1位であり、データベースの主要な選択肢のひとつです。

この記事では、WSL にて Python から PostgreSQL を利用するまでの手順をまとめます。

Python から PostgreSQL を操作

動作環境

  • Windows 11
  • WSL Ubuntu 20.04
  • Python 3.8.10
  • PostgreSQL 12.12

事前準備

WSL ディストリビューションの複製(非必須)

お試しで実行する場合は WSL Ubuntu イメージを複製しておくのがお勧めです。
本手順は必須ではありません。

各種インストール

Ubuntu パッケージのアップデート

初めに、Ubuntu パッケージを最新化しておきます。

$ sudo apt update
$ sudo apt upgrade
PostgreSQL

Ubuntu に PostgreSQL をインストールします。
今回は必須ではありませんが postgresql-contrib もインストールしておくと後々便利かと思います。

$ sudo apt install postgresql

インストール完了後、psql --version でバージョンの確認ができます。

$ psql --version
psql (PostgreSQL) 12.12 (Ubuntu 12.12-0ubuntu0.20.04.1)

WSL では、PostgreSQL のサービスが自動では起動しません。
service コマンドから手動で起動させます。

$ sudo service postgresql start
 * Starting PostgreSQL 12 database server

createuser コマンドで、データベース接続用のユーザ testuser を作成します。
-P オプション付きで実行すると、ここでパスワードの設定も可能です。
今回はパスワードは安直に、password と指定しています。

$ sudo -u postgres createuser -P testuser
Enter password for new role:
Enter it again:

createdb コマンドでデータベースを作成します。
オーナーには、先ほど作成した testuser を指定しておきます。

$ sudo -u postgres createdb testdb --encoding=UTF-8 --owner=testuser
Python パッケージ

Python のパッケージ管理ツール pip をインストールします。

$ sudo apt install python3-pip

次に psycopg2 をインストールしたいところですが、今の状態でインストールを試みると次のようなエラーが発生してしまいます。

    In file included from psycopg/psycopgmodule.c:28:
    ./psycopg/psycopg.h:36:10: fatal error: libpq-fe.h: No such file or directory
       36 | #include <libpq-fe.h>
          |          ^~~~~~~~~~~~
    compilation terminated.

上記のエラーを回避するために、libpq-dev をインストールしておきます。
これで libpq-fe.h が配置されます。

$ sudo apt install libpq-dev

最後に psycopg2 をインストールして準備完了です。

$ pip install psycopg2

Python ソースコード

psycopg2 を利用して PostgreSQL を操作するためのサンプルコードです。

import psycopg2

user = "testuser"
password = "password"
host = "localhost"
port = "5432"
dbname = "testdb"
connection = psycopg2.connect(f"postgresql://{user}:{password}@{host}:{port}/{dbname}")

cursor = connection.cursor()
cursor.execute("create table address (name text, phone text)")
cursor.execute("insert into address values('山田', '090-xxxx-xxxx')")
connection.commit()

cursor.execute("select * from address")
print(cursor.fetchone())
connection.close()

user, password, dbname には事前に作成したものを指定します。
コネクションおよびカーソルを取得し、11行目で address テーブルを新規作成しています。
12行目にて、address テーブルに山田の連絡先をインサートしています。
15行目で address テーブルの情報を取得しています。

以下、サンプルコードの実行結果です。
select 結果が出力されます。

$ python3 main.py
('山田', '090-xxxx-xxxx')

コード中にテーブルの作成が含まれていますので、2回実行すると次のようにエラーが発生します。
11~13行目をコメントアウトすれば、select の標準出力のみ実行され正常終了します。

$ python3 main.py
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    cursor.execute("create table address (name text, phone text)")
psycopg2.errors.DuplicateTable: relation "address" already exists

注意点

PostgreSQL が Ubuntu のサービスとして登録できているわけではないので、WSL が再起動されても PostgreSQL は自動的に起動してくれません。
そのような場合は psycopg2 が次のようなエラーを出力します。

psycopg2.OperationalError: could not connect to server: Connection refused
        Is the server running on host "localhost" (127.0.0.1) and accepting
        TCP/IP connections on port 5432?

PostgreSQL を起動するためには $ sudo service postgresql start のコマンドで手動で起動させましょう。
永続化された情報までは消えませんので、山田の連絡先は残存します。