PyMySQL 라이브러리 개요
PyMySQL은 파이썬에서 MySQL 데이터베이스와 통신하기 위해 설계된 순수 파이썬 클라이언트 라이브러리입니다. 과거에 주로 사용되던 MySQLdb가 파이썬 3 환경에서 호환성 문제가 있었던 것을 보완하여, 현재는 파이썬 3.x 환경에서 MySQL 연동을 위한 표준적인 선택지로 자리 잡았습니다.
이 라이브러리는 다음과 같은 핵심적인 특징을 보유하고 있습니다.
- DB-API 2.0 준수: 파이썬의 표준 데이터베이스 인터페이스 규격을 따르므로 학습 곡선이 낮습니다.
- 보안성: 매개변수화된 쿼리 방식을 지원하여 SQL Injection 공격을 효과적으로 방어할 수 있습니다.
- 유연한 트랜잭션 관리: Commit과 Rollback 기능을 통해 데이터의 무결성을 보장합니다.
- 순수 파이썬 구현: 별도의 C 라이브러리 설치 없이 pip를 통해 간편하게 설치하고 사용할 수 있습니다.
데이터베이스 테이블 생성
실습을 위해 다음과 같이 회원 정보를 저장할 수 있는 간단한 테이블 구조를 생성합니다.
CREATE TABLE `members` (
`member_id` INT AUTO_INCREMENT PRIMARY KEY,
`account_name` VARCHAR(50) NOT NULL,
`contact_email` VARCHAR(100) NOT NULL,
`access_token` VARCHAR(255) NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
데이터베이스 연결 설정
PyMySQL을 사용하여 데이터베이스에 접속하기 위한 기초 설정 코드입니다.
import pymysql
# 데이터베이스 연결 정보 설정
db_config = {
'host': 'localhost',
'user': 'db_user',
'password': 'db_password',
'database': 'service_db',
'charset': 'utf8mb4'
}
# 연결 객체 생성
connection = pymysql.connect(**db_config)
cur = connection.cursor()
데이터 삽입 (INSERT)
새로운 레코드를 추가할 때는 트랜잭션 처리를 위해 commit() 메서드를 호출해야 합니다.
try:
sql_insert = "INSERT INTO members (account_name, contact_email, access_token) VALUES (%s, %s, %s)"
record_data = ("dev_runner", "runner@example.com", "secure_token_123")
cur.execute(sql_insert, record_data)
connection.commit()
print("레코드가 성공적으로 추가되었습니다.")
except Exception as error:
connection.rollback()
print(f"데이터 삽입 중 오류 발생: {error}")
데이터 조회 (SELECT)
데이터를 조회한 후에는 fetchone()이나 fetchall()을 사용하여 결과를 파이썬 객체로 가져옵니다.
try:
search_name = "dev_runner"
sql_select = "SELECT member_id, account_name, contact_email FROM members WHERE account_name = %s"
cur.execute(sql_select, (search_name,))
member_list = cur.fetchall()
for member in member_list:
print(f"ID: {member[0]}, 이름: {member[1]}, 이메일: {member[2]}")
except Exception as error:
print(f"데이터 조회 중 오류 발생: {error}")
데이터 수정 (UPDATE)
조건에 맞는 특정 행의 데이터를 수정하는 방법입니다.
try:
new_email = "updated_runner@example.com"
target_account = "dev_runner"
sql_update = "UPDATE members SET contact_email = %s WHERE account_name = %s"
affected_rows = cur.execute(sql_update, (new_email, target_account))
connection.commit()
print(f"{affected_rows}개의 행이 업데이트되었습니다.")
except Exception as error:
connection.rollback()
print(f"데이터 수정 중 오류 발생: {error}")
데이터 삭제 (DELETE)
데이터를 삭제할 때도 무결성을 위해 예외 처리와 트랜잭션 관리가 필수적입니다.
try:
target_account = "dev_runner"
sql_delete = "DELETE FROM members WHERE account_name = %s"
cur.execute(sql_delete, (target_account,))
connection.commit()
print("데이터가 정상적으로 삭제되었습니다.")
except Exception as error:
connection.rollback()
print(f"데이터 삭제 중 오류 발생: {error}")
자원 해제
모든 데이터베이스 작업이 완료된 후에는 반드시 커서와 연결 객체를 닫아 시스템 자원을 반환해야 합니다.
cur.close()
connection.close()