[python] 파이썬에서 데이터베이스에서 데이터 수정하는 방법

데이터 수정 방법

1. SQLALCHEMY를 사용한 방법

SQLAlchemy를 사용해 데이터베이스에서 데이터를 수정하는 방법은 다음과 같습니다.

from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy import update

# 엔진 생성
engine = create_engine('sqlite:///example.db')

# 연결
connection = engine.connect()

# 테이블과 메타데이터 바인딩
metadata = MetaData()
table = Table('employees', metadata, autoload_with=engine)

# 쿼리 실행
stmt = (
    update(table).
    where(table.c.id == 1).
    values(name='New Employee Name')
)
connection.execute(stmt)

2. SQLite3를 이용한 방법

데이터를 직접 수정하는 경우에는 sqlite3 모듈과 SQL 쿼리를 사용하여 다음과 같이 데이터를 수정할 수 있습니다.

import sqlite3

# 연결
conn = sqlite3.connect('example.db')
cursor = conn.cursor()

# 쿼리 실행
cursor.execute("UPDATE employees SET name = ? WHERE id = ?", ('New Employee Name', 1))

# 변경사항 저장
conn.commit()

# 연결 종료
conn.close()

위 코드에서는 예시로 SQLite 데이터베이스를 사용했지만, 다른 데이터베이스에도 동일한 방법으로 데이터를 수정할 수 있습니다.

이처럼 파이썬에서는 SQLALCHEMY와 sqlite3를 사용하여 데이터베이스에서 데이터를 수정할 수 있습니다.