fetchone()은 데이터베이스 커서(cursor) 객체의 메서드 중 하나로, SQL 쿼리 실행 결과에서 단 한 개의 행(row)을 가져올 때 사용됩니다.
이전에 설명했던 DictCursor를 사용했다면, fetchone()의 결과는 딕셔너리 형태의 단일 행이 될 것이고, 일반 커서를 사용했다면 튜플 형태의 단일 행이 될 것입니다.
fetchone()의 특징 및 동작 방식:
예시:
import psycopg2
from psycopg2.extras import DictCursor # DictCursor를 사용한다고 가정
# 데이터베이스 연결 (예시)
conn = psycopg2.connect(
database="my_db",
user="user",
password="password",
host="localhost",
port="5432"
)
# DictCursor 생성
cursor = conn.cursor(cursor_factory=DictCursor)
# 쿼리 실행 (users 테이블에서 모든 사용자 조회)
cursor.execute("SELECT id, name, email FROM users;")
# 첫 번째 행 가져오기
first_user = cursor.fetchone()
if first_user:
print("첫 번째 사용자:", first_user) # {'id': 1, 'name': 'Alice', 'email': 'alice@example.com'}
print("사용자 이름:", first_user['name']) # Alice
else:
print("가져올 사용자가 없습니다.")
# 두 번째 행 가져오기 (커서가 다음 위치로 이동했으므로)
second_user = cursor.fetchone()
if second_user:
print("두 번째 사용자:", second_user) # {'id': 2, 'name': 'Bob', 'email': 'bob@example.com'}
else:
print("두 번째 사용자가 없습니다.")
# 더 이상 행이 없을 때
third_user = cursor.fetchone() # 더 이상 행이 없으면 None 반환
if third_user is None:
print("더 이상 가져올 사용자가 없습니다. (None 반환 확인)")
cursor.close()
conn.close()
fetchone()과 fetchall(), fetchmany() 비교:
fetchall()
: 쿼리 결과의 남아있는 모든 행을 리스트 형태로 가져옵니다. (예: [{'id': 1, 'name': 'A'}, {'id': 2, 'name': 'B'}]) 한 번 호출하면 커서가 결과 집합의 끝으로 이동합니다.