import psycopg2
## 데이터베이스와 연결
connection = psycopg2.connect('dbname=example', password = '*****')
## open session -- start transactions
## the cursor is offered by the connection object as a result of connectiong to psycopg2
cursor = connection.cursor()
## cursor is an interface that allows you to start queuing up work and transactions.
cursor.execute('''
CREATE TABLE table2 (
id INTEGER PRIMARY KEY,
completed BOOLEAN NOT NULL DEFAULT False
);
''')
cursor.execute('INSERT INTO table2 (id, completed) VALUES (1, true);')
## 만들었던 트랜젝션들을 커밋함
connection.commit()
## 더이상 트랜잭션을 만들지 않고 커밋하고 싶지 않다면
connection.close()
cursor.close()
# ## version1. Using %s, passing in a tuple as the 2nd argument in cusror.execute()
# cursor.execute('INSERT INTO table2 (id, completed) VALUES (%s, %s);', (1, True))
# ## version2. Using named string parameters %(foo)s, passing in a dictionary instead.
# cursor.execute('INSERT INTO table2 (id, completed) VALUES (%(id)s, %(completed)s);',
# {'id': 4, 'completed': False}
# )
## imporve code quality
SQL = 'INSERT INTO table2 (id, completed) VALUES (%(id)s, %(completed)s);'
data = {'id': 4, 'completed': False}
cursor.execute(SQL, data)
Fetch: Retrieving data and then moving it to an alternate location or displaying it.
cursor.execute('SELECT * from table2;')
# result = cursor.fetchall()
# print('fetchall', result)
result = cursor.fetchmany(2)
print('fetchmany', result)
result2 = cursor.fetchone()
print('fetchone', result2)
result3 = cursor.fetchone()
print('fetchone', result3)
주의할점: fetch를 할 때에는 바로 전에 execute한 결과만을 가져온다. 만약 레코드가 3개 있다고 했을 때 위의 코드를 실행하면
fetchmany [(1, True), (4, False)]
fetchone (3, True)
fetchone None
이와 같은 결과가 나오고 만약 마지막 .fetchone()
을 하기 바로 전에 select * from table2
를 한번 더 .execute()
했다면
fetchmany [(1, True), (4, False)]
fetchone (3, True)
fetchone (1, True)
이와 같은 결과가 나온다.
conn = psycopg2.connect(...)
cursor = conn.cursor()
cursor.execute()
cursor.commit()
cursor.rollback()
cursor.fetchall()
cursor.fetchmany(3)
cursor.fetchone()
cursor.close()
conn.close()