
psycopgSQL-relaySQL-relay는 여러 가지 언어를 같이 지원psycopg가 Python 전용 드라이버이자 정식 드라이버pip 이용해서 설치pip install psycopg2-binarypsycopg2 패키지의 connect 메서드를 이용하면 됨# 예제 1
connection = psycopg2.connect(
"host=192.168.0.1 dbname=postgres user=postgres password=1234 port=5432"
)
# 예제 2
connection = psycopg2.connect(
host="192.168.0.1",
dbname="postgres",
user="postgres",
password="1234",
port=5432
)
cursor라는 인스턴스를 만들어서 그 인스턴스를 통해 데이터 조작을 진행cursor = connection.cursor()cursor를 통해 데이터베이스와 연동 가능cursor.execute(
"CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);"
)
connection.commit()
CREATE TABLE 명령어를 이용하여 테이블 생성을 시키고 commit() 메서드를 호출하여 실제로 데이터베이스에 변경을 일으킴rollback() 메서드를 호출cursor.execute(
"INSERT INTO test (id, num, data) VALUES (%s, %s, %s);",
(1, 100, "data01")
)
execute 메서드의 첫 번째 파라미터는 실행시키려는 SQL문을 지정%s는 placeholder라고 함string을 넘길 경우 %s를 '%s'로 지정하지 않도록 주의delete나 update문도 마찬가지로 %s placeholder를 이용해서 쿼리문을 작성해서 실행시키면 됨# update 예제
cursor.execute(
"UPDATE test SET num=num+%s where id = %s",
(10, 1)
)
connection.commit()
# delete 예제
cursor.execute(
"DELETE FROM test where id = %s',
(1)
)
connection.commit()
select문도 execute 메서드를 이용하여 쿼리를 실행Fetch***() 메서드를 이용하여 가져온 데이터를 로컬 변수에 저장하는 부분이 추가됨cursor.execute("SELECT * FROM test")
(id, num, data) = cursor.fetchone()
print(f"{id}, {num}, {data}")
fetchone(), fetchmany(), fetchall() 3개의 메서드가 있는데 이름에서 알 수 있듯이 한 개 또는 여러 개 또는 전부 가져오는 메소 드fetchall() 같은 경우 아주 큰 테이블에 실행할 경우 문제가 생길 수 있으니 잘 고려해서 사용해야 함tuple이 기본이고 -many나 -all류의 메서드는 array of tuple 타입이 됨cursor.close()
connection.close()
cursor의 경우 Python의 with 키워드를 통해 자동 리소스 해제도 가능conn = psycopg2.connect('.....')
# 예제 1
with conn:
with conn.cursor() as cursor:
cursor.execute(sql_query)
conn.commit()
conn.close()
# 예제 2
from contextlib import closing
with closing(conn.cursor()) as cursor:
cursor.execute(sql_query)
conn.commit()
Tip! 추가 내용
- 명령을 처리할때 사용하는
cursor함수- SQL 명령을 처리하기 위한
execute함수- 데이터베이스에 트랜잭션 변화가 있을때 커밋을 해주는
commit함수# cusor cursor = db.cursor() # execute def execute(self,query,args={}): self.cursor.execute(query, args) row = self.cursor.fetchall() return row # commit def commit(self): self.cursor.commit()