FOREST_CHOI's BLOG

Python Connect Postgres Database 본문

프로그래밍/Python(Algo, tips, etc...)

Python Connect Postgres Database

Forest_Choi 2022. 10. 7. 23:18
728x90

Python과 PostgreSQL을 연결하기 위해서는 psycopg2 라는 라이브러리가 필요하다.

 

현재 psycopg3가 나오고 있는상황이지만, 구글링 결과 여전히 psycopg2를 많이 사용하고 있어 많은 정보를 얻을 수 있어 psycopg2로 적용을 하였다.

 

나는 pip로 다운받지않고 tar파일을 받아서 import해주었다.

https://pypi.org/project/psycopg2/

 

psycopg2

psycopg2 - Python-PostgreSQL Database Adapter

pypi.org

여기서 다운받으면된다.

 

 

 

import psycopg2 as pg2

다운 받은 후 위와같이 import해준다.

근데 연결해야하는 데이터베이스가 AWS EC2에 있는 Postgres였기 때문에 ssh tunneling을 사용하여 연결하였다.

 

from sshtunnel import SSHTunnelForwarder
import psycopg2 as pg2

def connect_server(serverHost, serverPort, ssh_username, ssh_private_key, remote_bind_address_host,
                   remote_bind_address_port):
    try:
        server = SSHTunnelForwarder(
            (serverHost, serverPort),
            ssh_username=ssh_username,
            ssh_private_key=ssh_private_key,
            remote_bind_address=(remote_bind_address_host, remote_bind_address_port)
        )
        server.start()

        print("server connection success")
        print()
        return server
    except:
        print("server connection fail")


def connect_database(db_name, db_user, db_pw, db_host, db_port):
    conn = pg2.connect(database=db_name, user=db_user, password=db_pw, host=db_host, port=db_port)

    print("database connection success")
    print()
    return conn


if __name__ == '__main__':
    server = connect_server('{ Server IP} ', { Port }, "{Server User} ", "{ .pem file }", "127.0.0.1", 25434)
    conn = connect_database("gis", "docker", "docker", "127.0.0.1", server.local_bind_port)  # 5432 넣으면 안됨

EC2의 postgres 가 docker로 띄워져있고 포트포워딩을 25434 -> 5432로 해 줬기 때문에 25434이다.

728x90

'프로그래밍 > Python(Algo, tips, etc...)' 카테고리의 다른 글

Mojo  (0) 2023.05.16
Python 경로(상대경로 삽질...)  (0) 2023.05.08
Python Overflow?  (0) 2022.10.08
Comments