[python] 파이썬 데이터베이스 작업 시 예외 처리 방법

파이썬을 사용하여 데이터베이스 작업을 수행할 때 예외 처리는 매우 중요합니다. 데이터베이스 연결, 쿼리 실행, 결과 처리 등 여러 부분에서 예외가 발생할 수 있기 때문입니다. 이번 블로그에서는 파이썬 데이터베이스 작업 시 발생할 수 있는 주요 예외 상황과 그에 대한 적절한 처리 방법에 대해 알아보겠습니다.

1. 데이터베이스 연결 예외 처리

import psycopg2

try:
    conn = psycopg2.connect(database="dbname", user="user", password="password", host="host", port="port")
except psycopg2.OperationalError as e:
    print(f"Failed to connect to database: {e}")

위의 예제에서는 psycopg2를 사용하여 PostgreSQL 데이터베이스에 연결하는 과정에서 발생할 수 있는 OperationalError를 처리하는 방법을 보여줍니다.

2. 쿼리 실행 예외 처리

import psycopg2

conn = psycopg2.connect(database="dbname", user="user", password="password", host="host", port="port")
cur = conn.cursor()

try:
    cur.execute("SELECT * FROM table_name")
except psycopg2.Error as e:
    print(f"Failed to execute query: {e}")

위의 예제는 데이터베이스에서 쿼리를 실행할 때 발생할 수 있는 예외를 처리하는 방법을 보여줍니다.

3. 결과 처리 예외 처리

import psycopg2

conn = psycopg2.connect(database="dbname", user="user", password="password", host="host", port="port")
cur = conn.cursor()

try:
    cur.execute("SELECT * FROM table_name")
    rows = cur.fetchall()
except psycopg2.Error as e:
    print(f"Failed to fetch result: {e}")

위의 예제는 데이터베이스에서 결과를 가져오는 과정에서 발생할 수 있는 예외를 처리하는 방법을 보여줍니다.

결론

데이터베이스 작업 시 예외 처리는 신중하게 고려되어야 합니다. 각 단계별로 발생할 수 있는 예외를 고려하고 적절한 예외 처리 코드를 작성하는 것이 중요합니다. 이를 통해 안정적인 데이터베이스 연동 및 안정적인 애플리케이션을 구축할 수 있습니다.