業界トップクラスの求人数を誇る転職エージェントPR

リクルートグループのコネクションを活かした非公開求人も充実、他にはない好条件の求人と出会える

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?

More than 5 years have passed since last update.

リモートのpython3(psycopg2)からubuntu16.04@AWSのpostgresqlに接続

Last updated at Posted at 2019-10-28

前提

①ubuntu16.04をAWS上で立ち上げpython3,postgresqlをインストール完了
②python3でpsyopg2が扱える

以下はSelectクエリの実行例です。リモートで実行する前にローカルで問題なく実行できることを確認しておきます。

#################################
###    Selectクエリの実行例    ###
#################################
import psycopg2, psycopg2.extras

# 1. Postgesqlの接続設定(設定に合わせて修正してください)
# HOST     = "localhost  #ローカルで実行するとき
HOST     = "172.0.0.1"  
PORT     = "5432"
DBNAME   = "postgres"
USER     = "postgres"
PASSWORD = "p@ssword"
CREDENTIAL = "host={h} port={p} dbname={db} user={u} password={pa}"\
	.format(h=HOST,p=PORT,db=DBNAME,u=USER,pa=PASSWORD)

QUERY = "Select * from exercise" #テーブル名は任意に設定してください


# 2. Postgresに接続してクエリを実行
with psycopg2.connect(CREDENTIAL) as conn:
    with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
        
        # クエリ実行
        cur.execute(QUERY) 
        rows = cur.fetchall()

# 3. 結果を表示
print(rows[0])

やったこと

①セキュリティグループの設定(下図の赤枠の設定)

Postgresql_リモート.jpg
※「0.0.0.0/0」はすべてのリモートアクセスを許可しているので注意してください。

セキュリティグループの設定をする前にリモート接続を実行すると以下の通りTimeoutエラーが出ました。


OperationalError: could not connect to server: Connection timed out (0x0000274C/10060)
	Is the server running on host "【リモートIP】" and accepting
	TCP/IP connections on port 5432?

セキュリティグループの設定にPostgresqlを追加すると以下のRefusedエラーに代わりました。これでTCPの設定はOKです。

OperationalError: could not connect to server: Connection refused (0x0000274D/10061)
	Is the server running on host "【リモートIP】" and accepting
	TCP/IP connections on port 5432?
②postgresqlの設定ファイルの修正とpostgresqlの再起動

ph_hba.conf と postgresql.confのファイルを修正します。そして修正後にpostgesqlを再起動するのですが以下のブログの最後の方で詳しく説明されていますのでこちらを参考ください。
https://qiita.com/ibara1454/items/40ce2d82926f48cf02bc

以上で終了です。ここまでの設定をすれば接続してクエリがリモートから実行できました。
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
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?