cx_Oracle: 결과 세트 반복 방법

2024-07-27

fetch() 함수 사용

fetch() 함수는 결과 세트에서 한 행씩 반환합니다. 각 반환 값은 튜플 형식이며, 각 열의 값을 나타냅니다.

import cx_Oracle

connection = cx_Oracle.connect('user/password@database')
cursor = connection.cursor()

cursor.execute('SELECT * FROM customers')

while True:
    row = cursor.fetch()
    if row is None:
        break
    print(row)

connection.close()

fetchall() 함수는 결과 세트의 모든 행을 한 번에 리스트 형식으로 반환합니다.

import cx_Oracle

connection = cx_Oracle.connect('user/password@database')
cursor = connection.cursor()

cursor.execute('SELECT * FROM customers')

rows = cursor.fetchall()
for row in rows:
    print(row)

connection.close()

fetchone() 함수는 결과 세트에서 다음 행을 한 행씩 반환합니다. 이 함수는 반복 루프에서 사용하기에 유용합니다.

import cx_Oracle

connection = cx_Oracle.connect('user/password@database')
cursor = connection.cursor()

cursor.execute('SELECT * FROM customers')

while True:
    row = cursor.fetchone()
    if row is None:
        break
    print(row)

connection.close()

iterrows() 함수 사용

iterrows() 함수는 결과 세트의 각 행을 튜플 형식으로 반환하며, 첫 번째 요소는 행 번호이고 두 번째 요소는 행 데이터입니다.

import cx_Oracle

connection = cx_Oracle.connect('user/password@database')
cursor = connection.cursor()

cursor.execute('SELECT * FROM customers')

for row_num, row in cursor.iterrows():
    print(f'Row {row_num}: {row}')

connection.close()

for 루프 사용

for 루프를 사용하여 결과 세트의 각 행을 반복할 수도 있습니다.

import cx_Oracle

connection = cx_Oracle.connect('user/password@database')
cursor = connection.cursor()

cursor.execute('SELECT * FROM customers')

for row in cursor:
    print(row)

connection.close()

참고:

  • 결과 세트를 반복한 후에는 반드시 cursor.close() 함수를 호출하여 커서를 닫아야 합니다.
  • 결과 세트는 메모리에 상당한 공간을 차지할 수 있으므로, 필요한 경우에만 반복하는 것이 좋습니다.
  • 결과 세트의 크기가 큰 경우, iterrows() 함수를 사용하는 것이 더 효율적일 수 있습니다.



예제 코드: cx_Oracle을 사용하여 Oracle 데이터베이스에 연결하고 데이터를 조작하는 방법

필수 조건:

  • Oracle 데이터베이스
  • Python 3.x
  • cx_Oracle 라이브러리

설치:

  1. cx_Oracle 라이브러리를 설치합니다.
    pip install cx_Oracle
    
  2. TNSNAMES 파일을 구성합니다. TNSNAMES 파일은 Oracle 데이터베이스에 대한 연결 정보를 포함합니다. 자세한 내용은 Oracle 설명서를 참조하십시오.

코드:

import cx_Oracle

# 데이터베이스 연결
connection = cx_Oracle.connect('user/password@database')

# 커서 생성
cursor = connection.cursor()

# 데이터 삽입
cursor.execute('INSERT INTO customers (name, email, phone) VALUES (:name, :email, :phone)',
                name='John Doe', email='[email protected]', phone='123-456-7890')

# 커밋
connection.commit()

# 데이터 선택
cursor.execute('SELECT * FROM customers')
rows = cursor.fetchall()

for row in rows:
    print(row)

# 데이터 업데이트
cursor.execute('UPDATE customers SET email = :email WHERE id = :id',
                email='[email protected]', id=1)

# 커밋
connection.commit()

# 데이터 삭제
cursor.execute('DELETE FROM customers WHERE id = :id', id=2)

# 커밋
connection.commit()

# 커서 및 연결 닫기
cursor.close()
connection.close()

설명:

  • 이 코드는 cx_Oracle을 사용하여 Oracle 데이터베이스에 연결합니다.
  • cursor.execute() 함수를 사용하여 SQL 쿼리를 실행합니다.
  • cursor.fetch*() 함수를 사용하여 결과 세트를 가져옵니다.
  • connection.commit() 함수를 사용하여 변경 사항을 저장합니다.
  • cursor.close() 함수를 사용하여 커서를 닫습니다.
  • connection.close() 함수를 사용하여 데이터베이스 연결을 닫습니다.



cx_Oracle 결과 세트 반복: 대체 방법

RowProxy 객체 사용:

cx_Oracle은 결과 세트의 각 행에 대한 RowProxy 객체를 제공합니다. RowProxy 객체는 딕셔너리와 유사하며, 열 이름을 키로 사용하여 열 값에 액세스할 수 있습니다.

import cx_Oracle

connection = cx_Oracle.connect('user/password@database')
cursor = connection.cursor()

cursor.execute('SELECT * FROM customers')

while True:
    row = cursor.fetchone()
    if row is None:
        break
    print(row['name'], row['email'], row['phone'])

connection.close()

namedtuple 사용:

namedtuple 모듈을 사용하여 결과 세트의 각 행에 대한 namedtuple 객체를 만들 수 있습니다. namedtuple 객체는 튜플과 유사하지만, 각 요소에 이름이 지정되어 있어 더욱 명확하게 사용할 수 있습니다.

import cx_Oracle
from collections import namedtuple

connection = cx_Oracle.connect('user/password@database')
cursor = connection.cursor()

cursor.execute('SELECT * FROM customers')

Customer = namedtuple('Customer', [col.name for col in cursor.description])

for row in cursor:
    customer = Customer(*row)
    print(customer.name, customer.email, customer.phone)

connection.close()

Pandas 라이브러리 사용:

Pandas 라이브러리는 데이터 분석 및 조작을 위한 강력한 도구입니다. cx_Oracle 결과 세트를 Pandas DataFrame으로 변환하여 다양한 Pandas 함수를 사용하여 결과 세트를 처리할 수 있습니다.

import cx_Oracle
import pandas as pd

connection = cx_Oracle.connect('user/password@database')
cursor = connection.cursor()

cursor.execute('SELECT * FROM customers')

df = pd.DataFrame(cursor.fetchall(), columns=[col[0] for col in cursor.description])

print(df)

connection.close()
  • 위의 방법들은 각자 장단점이 있습니다. 특정 상황에 가장 적합한 방법을 선택하는 것이 중요합니다.
  • RowProxy 객체는 간단하고 빠르지만, 열 이름을 기억해야 합니다.
  • namedtuple 객체는 더욱 명확하지만, 코드를 추가로 작성해야 합니다.
  • Pandas 라이브러리는 데이터 분석에 유용하지만, cx_Oracle만으로 사용하는 것보다 더 많은 코드가 필요합니다.

python sql database

python sql database