다른 명령
파이썬 데코레이터
assignment 데코레이터를 사용하여 데이터베이스(DB) 접속
- 반복적인 DB 연결/해제 로직을 깔끔하게 감싸는 데 유용합니다.
기본 구조
- 데코레이터 함수: DB에 연결하고, wrapped 함수 실행 후 연결 해제
- 커넥션 객체: sqlite3, psycopg2, cx_Oracle, pymysql 등 사용 가능
- 활용 예시: 쿼리 실행 시 자동으로 연결, 종료를 처리
예제 (SQLite 기준)
import sqlite3 from functools import wraps # 데코레이터 정의 def with_db_connection(func): @wraps(func) def wrapper(*args, **kwargs): conn = sqlite3.connect("example.db") # 연결 try: result = func(conn, *args, **kwargs) # 함수에 conn 전달 conn.commit() return result except Exception as e: conn.rollback() raise e finally: conn.close() # 연결 종료 return wrapper # 실제 사용 @with_db_connection def create_table(conn): cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT ) """) @with_db_connection def insert_user(conn, name): cursor = conn.cursor() cursor.execute("INSERT INTO users (name) VALUES (?)", (name,)) @with_db_connection def get_users(conn): cursor = conn.cursor() cursor.execute("SELECT * FROM users") return cursor.fetchall() # 함수 실행 create_table() insert_user("Alice") insert_user("Bob") print(get_users()) # [('1', 'Alice'), ('2', 'Bob')]
장점
- 중복되는 connect() / close() 코드 제거
- 트랜잭션 자동 처리 (commit, rollback)
- 커넥션 전달을 깔끔하게 통제 가능
다른 DB 예시 (psycopg2, cx_Oracle, pymysql)
- 필요에 따라 아래처럼 응용 가능:
def with_pg_connection(func): @wraps(func) def wrapper(*args, **kwargs): conn = psycopg2.connect( host="localhost", database="mydb", user="myuser", password="mypassword" ) try: return func(conn, *args, **kwargs) finally: conn.close() return wrapper
- 추가적으로 필요하신 구조
- 커넥션 풀 연동 (cx_Oracle.SessionPool, psycopg2.pool)
- 비동기 데코레이터 (async with)
- JSON 설정 기반 자동 커넥션 선택