티스토리 뷰

728x90
반응형

PostgreSQL은 강력하고 널리 사용되는 오픈 소스 관계형 데이터베이스 관리 시스템(RDBMS)입니다. Python에서 PostgreSQL과 상호작용하려면 SQLAlchemy와 psycopg2라는 두 가지 인기 있는 라이브러리를 사용할 수 있습니다. 이 글에서는 SQLAlchemy와 psycopg2를 사용하여 PostgreSQL 데이터베이스를 연동하고 데이터를 처리하는 방법을 단계별로 알아보겠습니다.


1. 주요 라이브러리 소개

SQLAlchemy

SQLAlchemy는 Python에서 데이터베이스와 상호작용하기 위한 강력한 ORM(Object Relational Mapper) 및 SQL 툴킷입니다. SQLAlchemy는 데이터베이스 작업을 객체 지향 방식으로 처리할 수 있도록 지원하며, 복잡한 쿼리도 쉽게 작성할 수 있게 해줍니다.

psycopg2

psycopg2는 PostgreSQL 데이터베이스와 상호작용하기 위한 Python용 라이브러리입니다. SQLAlchemy가 고수준 인터페이스를 제공하는 반면, psycopg2는 저수준에서 직접 SQL 명령을 실행할 수 있는 방법을 제공합니다.


2. 라이브러리 설치

먼저, 필요한 라이브러리를 설치합니다. 아래 명령어를 실행하세요:

pip install sqlalchemy psycopg2

3. PostgreSQL 데이터베이스 설정

PostgreSQL 서버에 데이터베이스를 생성합니다. 예제에서는 데이터베이스 이름을 example_db로 지정했습니다. 명령어는 다음과 같습니다:

CREATE DATABASE example_db;

4. SQLAlchemy와 psycopg2를 사용한 데이터베이스 연결

(1) SQLAlchemy를 사용한 데이터베이스 연결 설정

Python에서 PostgreSQL에 연결하려면 데이터베이스 URL을 구성해야 합니다. SQLAlchemy의 연결 문자열 형식은 다음과 같습니다:

postgresql+psycopg2://<username>:<password>@<host>:<port>/<database_name>

예를 들어, 로컬 호스트에서 example_db에 연결하려면 다음과 같이 작성합니다:

from sqlalchemy import create_engine

def connect_with_sqlalchemy():
    # PostgreSQL 연결 문자열 구성
    db_url = "postgresql+psycopg2://postgres:yourpassword@localhost/example_db"

    # 엔진 생성
    engine = create_engine(db_url)
    print("SQLAlchemy로 데이터베이스에 연결되었습니다.")
    return engine

create_engine 함수는 SQLAlchemy의 핵심 엔진을 생성하며, 이를 통해 데이터베이스와의 상호작용이 가능합니다.

(2) psycopg2를 사용한 데이터베이스 연결 설정

psycopg2를 사용하여 PostgreSQL 데이터베이스에 연결하려면 다음과 같이 설정합니다:

import psycopg2

def connect_with_psycopg2():
    # psycopg2로 데이터베이스 연결
    connection = psycopg2.connect(
        host="localhost",
        database="example_db",
        user="postgres",
        password="yourpassword"
    )

    cursor = connection.cursor()
    print("psycopg2로 데이터베이스에 연결되었습니다.")
    return connection, cursor

위 코드는 PostgreSQL 서버에 연결을 설정하고, SQL 명령을 실행할 수 있는 커서를 생성합니다.


5. SQLAlchemy와 ORM 사용하기

SQLAlchemy를 사용하면 테이블 구조를 Python 클래스와 매핑하여 객체 지향적으로 데이터베이스 작업을 처리할 수 있습니다.

테이블 정의

아래는 SQLAlchemy의 ORM을 사용해 users라는 테이블을 정의하는 예제입니다:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

# ORM 기반 클래스 생성
Base = declarative_base()

def define_users_table():
    class User(Base):
        __tablename__ = 'users'

        id = Column(Integer, primary_key=True)
        name = Column(String, nullable=False)
        age = Column(Integer, nullable=False)

    return User

# 테이블 생성 함수
def create_users_table(engine):
    Base.metadata.create_all(engine)
    print("테이블이 생성되었습니다.")

데이터 삽입

from sqlalchemy.orm import sessionmaker

def insert_user(engine, name, age):
    Session = sessionmaker(bind=engine)
    session = Session()

    User = define_users_table()
    new_user = User(name=name, age=age)
    session.add(new_user)
    session.commit()
    print(f"사용자 {name}이 추가되었습니다.")

데이터 조회

def get_all_users(engine):
    Session = sessionmaker(bind=engine)
    session = Session()

    User = define_users_table()
    users = session.query(User).all()
    for user in users:
        print(user.name, user.age)

6. psycopg2로 SQL 실행하기

SQLAlchemy 대신 psycopg2를 사용해 직접 SQL 명령을 실행할 수도 있습니다.

테이블 생성

def create_table_with_psycopg2(cursor):
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id SERIAL PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        age INT NOT NULL
    );
    ''')
    print("psycopg2로 테이블이 생성되었습니다.")

데이터 삽입

def insert_user_with_psycopg2(cursor, connection, name, age):
    cursor.execute('INSERT INTO users (name, age) VALUES (%s, %s)', (name, age))
    connection.commit()
    print(f"사용자 {name}이 추가되었습니다.")

데이터 조회

def get_all_users_with_psycopg2(cursor):
    cursor.execute('SELECT * FROM users')
    for row in cursor.fetchall():
        print(row)

7. SQLAlchemy vs psycopg2

SQLAlchemy의 장점

  1. 객체 지향적 데이터베이스 관리.
  2. 데이터베이스 독립성(다른 RDBMS에서도 재사용 가능).
  3. 복잡한 쿼리도 간단하게 작성 가능.

psycopg2의 장점

  1. SQLAlchemy보다 경량.
  2. 직접 SQL을 실행하므로 세부적인 제어 가능.
  3. 간단한 작업에서 빠른 성능 제공.

8. 결론

SQLAlchemy와 psycopg2는 각각의 강점이 있습니다. 복잡한 프로젝트에서 SQLAlchemy의 ORM 기능을 활용하면 개발 생산성을 높일 수 있으며, 간단한 작업이나 성능이 중요한 경우 psycopg2를 사용하는 것이 적합합니다. 두 도구를 적절히 조합하여 효율적인 데이터베이스 연동을 구현해보세요!

728x90
반응형