0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pythonでpostgresqlにアクセスする

0
Posted at

はじめに

PythonからPostgreSQLへ接続する場合、psycopg2というライブラリを利用する方法があります。
RockyLinux にはデフォルトでインストールされていないため、インストールの手順を備忘として下記に記載します。

インストール

pip3インストール

psycopg2 は pip3 でインストールするため、事前に pip3 をインストールします
dnf install python3-pip

インストールされたことを確認します
which pip3

# which pip3
/usr/bin/pip3
#

psycopg2 インストール

※rootユーザでインストールしようとすると警告メッセージが出力されますが、インストール自体は実行されます
pip3 install psycopg2-binary

# pip3 install psycopg2-binary
Collecting psycopg2-binary
  Downloading psycopg2_binary-2.9.12-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (4.9 kB)
Downloading psycopg2_binary-2.9.12-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (4.3 MB)
   qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq 4.3/4.3 MB 10.1 MB/s eta 0:00:00
Installing collected packages: psycopg2-binary
Successfully installed psycopg2-binary-2.9.12
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
#

インストールされたことを確認します
pip3 list | grep psycopg2

# pip3 list | grep psycopg2
psycopg2-binary           2.9.12
#

PostgreSQL へアクセス

PostgreSQL アクセス用コード作成

下記は Redmine がインストールされた環境で実行しているため、ほかの環境で実行する場合は適宜 database、user、password の内容を変更してください

# vi test.py
import psycopg2

conn = psycopg2.connect(
    host="127.0.0.1",
    port=5432,
    database="redmine",
    user="redmine",
    password="xxxxxxxxxx"
)

cur = conn.cursor()

cur.execute("SELECT id, login FROM users order by id")

for row in cur.fetchall():
    print(row)

cur.close()
conn.close()

#

PostgreSQL アクセス確認

python3 test.py

# python3 test.py
(1, 'admin')
(2, '')
(3, '')
(4, '')
#

以上になります

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?