python의 경우 psycopg2를 import해서 postgresql과 연결하는 방법이 있습니다.
https://www.postgresqltutorial.com/postgresql-python/connect/
PostgreSQL Python: Connect To PostgreSQL Database Server
Summary: in this tutorial, you will learn how to connect to the PostgreSQL database server in the Python program using the psycopg database adapter. Install the psycopg2 module First, visit the psycopg2 package here. Second, use the following command line
www.postgresqltutorial.com
위의 튜토리얼 실습을 통해 psycopg2에 대해 익혀 봅시다
$ pip install psycopg2
sql shell 에서 새database로 suppliers 생성
CREATE DATABASE suppliers;
database.ini 파일 database 설정 입력
[postgresql]
host=localhost
database=suppliers
user=postgres
password=
config.py에 아래와 같이 config 함수 정의
from configparser import ConfigParser
def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
test.py를 만들어서 postgresql에 연결해봅시다.
import psycopg2
from config import config
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
connect()
# psycopg2 > connect > cursor
connect()에 db 설정값을 입력해서 접속하고 # conn = psycopg2.connect(**params)
cursor를 통해 SQL문을 실행 # cur = conn.cursor() #cur.execute('SELECT version()')
fetch를 통해 결과값을 가져옵니다. # db_version = cur.fetchone()
fetch: fetchone - 한개 값 return / fetchmany - 지정개수 retrn / fetchall - 모두 return
ex) cursor.fetchone()
cursor.fetchmany(size=4)
cursor.fetchall()
추가 참고 블로그: https://yahwang.github.io/posts/66
pymysql(MySQL)과 psycopg2(PostgreSQL) 사용하기 - YA-Hwang 기술 블로그
Python SQL client 라이브러리인 pymysql(MySQL)과 psycopg2(PostgreSQL) 사용법을 알아본다.
yahwang.github.io
need_to_study
cursor.copy_from
pymysql
psycopg2-binary