IT/Python

[Python] MySQL과 파이썬 연동하기

멋진 선배 2025. 1. 15. 21:06
반응형

파이썬에서 MySQL 데이터베이스를 연동하고 활용하는 방법에 대해서 자세하게 알아보도록 하겠습니다. 데이터베이스 연동은 웹 개발이나 데이터 분석에서 매우 중요한 기술 입니다.

사전 준비하기

MySQL 서버 설치

Python용 MySQL 커넥터 설치

pip install mysql-connector-python

데에터베이스 연결하기

MySQL과 파이썬을 연결하는 기본코드 입니다.

import mysql.connector

try:
    connection = mysql.connector.connect(
        host="localhost",
        user="your_username",
        password="your_password",
        database="your_database"
    )
    
    if connection.is_connected():
        print("MySQL 데이터베이스에 성공적으로 연결되었습니다!")

except mysql.connector.Error as err:
    print(f"에러가 발생했습니다: {err}")

데이터 베이스 생성하기

새로운 데이터베이스를 만들어볼까요?

def create_database():
    try:
        connection = mysql.connector.connect(
            host="localhost",
            user="your_username",
            password="your_password"
        )
        cursor = connection.cursor()
        cursor.execute("CREATE DATABASE IF NOT EXISTS my_database")
        print("데이터베이스가 성공적으로 생성되었습니다!")
        
    except mysql.connector.Error as err:
        print(f"에러: {err}")
        
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

테이블 생성하기

간단한 사용자 테이블을 만들어보겠습니다.

def create_table():
    try:
        connection = mysql.connector.connect(
            host="localhost",
            user="your_username",
            password="your_password",
            database="my_database"
        )
        cursor = connection.cursor()
        
        create_table_query = """
        CREATE TABLE IF NOT EXISTS users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255),
            email VARCHAR(255),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
        """
        cursor.execute(create_table_query)
        print("테이블이 성공적으로 생성되었습니다!")
        
    except mysql.connector.Error as err:
        print(f"에러: {err}")

데이터 추가하기

테이블에 데이터를 추가하는 방법을 알아볼까요?

def insert_user(name, email):
    try:
        connection = mysql.connector.connect(
            host="localhost",
            user="your_username",
            password="your_password",
            database="my_database"
        )
        cursor = connection.cursor()
        
        sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
        values = (name, email)
        cursor.execute(sql, values)
        
        connection.commit()
        print("데이터가 성공적으로 추가되었습니다!")
        
    except mysql.connector.Error as err:
        print(f"에러: {err}")

데이터 조회하기

저장된 데이터를 조회하는 방법 입니다.

def select_users():
    try:
        connection = mysql.connector.connect(
            host="localhost",
            user="your_username",
            password="your_password",
            database="my_database"
        )
        cursor = connection.cursor()
        
        cursor.execute("SELECT * FROM users")
        records = cursor.fetchall()
        
        for record in records:
            print(f"ID: {record[0]}")
            print(f"이름: {record[1]}")
            print(f"이메일: {record[2]}")
            print(f"생성일: {record[3]}\n")
            
    except mysql.connector.Error as err:
        print(f"에러: {err}")

안전한 데이터베이스 연결 관리

연결을 안전하게 관리하기 위한 with문을 사용하는 방법도 있습니다.

from contextlib import contextmanager

@contextmanager
def create_db_connection():
    connection = None
    try:
        connection = mysql.connector.connect(
            host="localhost",
            user="your_username",
            password="your_password",
            database="my_database"
        )
        yield connection
    finally:
        if connection and connection.is_connected():
            connection.close()

# 사용 예시
with create_db_connection() as connection:
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM users")
    records = cursor.fetchall()

실전 활용 팁

  1. 항상 연결을 닫아주세요.
  2. SQL 인젝션을 방지하기 위해 파라미터화된 쿼리를 사용하세요.
  3. 에러 처리를 항상 해주세요.
  4. 중요한 정보는 환경 변수로 관리하세요.

마무리

지금까지 MySQL과 파이썬 연동하는 기본적인 방법을 알아보았습니다. 이제 파이썬으로 데이터베이스를 다룰 수 있게 되었습니다. 실제 프로젝트를 적용하면서 다양한 경험을 쌓아보면 좋을 것 같습니다.

반응형