Python Database Integration


11. 데이터베이스 연동(Database Integration)

SQLite, MySQL, PostgreSQL 등의 데이터베이스 연동 (Connecting to SQLite, MySQL, PostgreSQL)

Python은 다양한 데이터베이스와의 연동을 지원합니다. 대표적으로 SQLite, MySQL, PostgreSQL과의 연동 방법을 살펴보겠습니다.

SQLite 연동

SQLite는 파일 기반의 경량 데이터베이스로, sqlite3 모듈을 사용하여 연동할 수 있습니다.

import sqlite3

# SQLite 데이터베이스 연결
conn = sqlite3.connect('example.db')
cursor = conn.cursor()

# 테이블 생성
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

# 데이터 삽입
cursor.execute("INSERT INTO users (name, age) VALUES ('Alice', 30)")
conn.commit()

# 데이터 조회
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
    print(row)

# 연결 종료
conn.close()

MySQL 연동

MySQL과의 연동은 mysql-connector-python 패키지를 사용하여 구현할 수 있습니다.

import mysql.connector

# MySQL 데이터베이스 연결
conn = mysql.connector.connect(
    host="localhost",
    user="yourusername",
    password="yourpassword",
    database="yourdatabase"
)
cursor = conn.cursor()

# 테이블 생성
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)''')

# 데이터 삽입
cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ('Bob', 25))
conn.commit()

# 데이터 조회
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
    print(row)

# 연결 종료
conn.close()

PostgreSQL 연동

PostgreSQL과의 연동은 psycopg2 패키지를 사용하여 구현할 수 있습니다.

import psycopg2

# PostgreSQL 데이터베이스 연결
conn = psycopg2.connect(
    host="localhost",
    database="yourdatabase",
    user="yourusername",
    password="yourpassword"
)
cursor = conn.cursor()

# 테이블 생성
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name VARCHAR(100), age INTEGER)''')

# 데이터 삽입
cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ('Charlie', 28))
conn.commit()

# 데이터 조회
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
    print(row)

# 연결 종료
conn.close()

ORM(Object-Relational Mapping) 사용 (Using ORM)

ORM은 데이터베이스와 객체 지향 프로그래밍 언어 간의 연결을 제공하여, 데이터베이스 연산을 객체 지향적으로 수행할 수 있게 합니다. Python에서 많이 사용하는 ORM은 SQLAlchemy와 Django ORM이 있습니다.

SQLAlchemy 사용

SQLAlchemy는 Python용 SQL 도구키트이자 ORM 라이브러리입니다.

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 데이터베이스 엔진 생성
engine = create_engine('sqlite:///example.db')
Base = declarative_base()

# 모델 정의
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

# 테이블 생성
Base.metadata.create_all(engine)

# 세션 생성
Session = sessionmaker(bind=engine)
session = Session()

# 데이터 삽입
new_user = User(name='David', age=35)
session.add(new_user)
session.commit()

# 데이터 조회
users = session.query(User).all()
for user in users:
    print(user.name, user.age)

# 세션 종료
session.close()

Django ORM 사용

Django ORM은 Django 프레임워크에서 제공하는 강력한 ORM 라이브러리입니다. Django 프로젝트의 models.py 파일에서 모델을 정의하고 사용합니다.

# models.py 파일
from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

# 데이터 삽입
user = User(name='Emma', age=22)
user.save()

# 데이터 조회
users = User.objects.all()
for user in users:
    print(user.name, user.age)

이와 같이 다양한 데이터베이스와의 연동 및 ORM을 활용하면, 데이터베이스 작업을 더 간편하고 효율적으로 수행할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *