1. Python과 MySQL 통합: 소개
Python은 다양한 데이터베이스 관리 시스템(DBMS)과 함께 사용할 수 있는 매우 유연한 프로그래밍 언어입니다. 특히 MySQL은 오픈 소스 관계형 데이터베이스로 널리 사용되며, Python과 결합하면 강력한 데이터 조작이 가능합니다.
이 기사에서는 Python을 사용하여 MySQL에 연결하고 데이터를 삽입, 조회, 업데이트 및 삭제와 같은 기본 데이터베이스 작업을 수행하는 방법을 설명합니다.
2. Python과 MySQL 통합을 위한 환경 설정
먼저, Python과 MySQL을 통합하기 위한 환경을 준비해야 합니다. 이 섹션에서는 필요한 소프트웨어를 설치하고 구성하는 방법을 설명합니다.
2.1 MySQL 설치
MySQL 설치 과정은 운영 체제에 따라 다릅니다. 아래는 각 OS에 대한 간단한 설치 방법입니다.
- For Windows : 공식 MySQL 웹사이트에서 설치 프로그램을 다운로드하고 설치 가이드를 따라 진행합니다.
- For macOS :
brew install mysql명령을 사용하여 Homebrew로 MySQL을 설치할 수 있습니다. - For Linux : Debian 기반 운영 체제에서는
sudo apt-get install mysql-server를 사용합니다.
2.2 Python 환경 설정
다음으로, Python 환경에 필요한 라이브러리를 설치합니다. Python에서 MySQL에 연결하려면 다음 라이브러리 중 하나가 필요합니다.
- mysql-connector-python : Oracle에서 제공하는 공식 MySQL 커넥터 라이브러리입니다.
- PyMySQL : MySQLdb와 호환되는 순수 Python 라이브러리입니다.
설치는 간단합니다—다음 명령을 실행하면 됩니다.
pip install mysql-connector-python
또는 PyMySQL을 사용하려면 다음 명령을 실행하십시오.
pip install pymysql
2.3 라이브러리 간 차이점
mysql-connector-python은 공식 MySQL 라이브러리로 뛰어난 성능과 포괄적인 지원을 제공합니다. 반면 PyMySQL은 가볍고 MySQLdb와 호환되는 기능이 필요할 때 적합합니다. 프로젝트 요구 사항에 따라 라이브러리를 선택해야 합니다.
3. Python을 사용하여 MySQL에 연결하는 기본 단계
Python을 사용하여 MySQL에 연결하는 것은 매우 간단합니다. 이 섹션에서는 MySQL에 연결하고 데이터베이스 내 테이블을 조작하는 방법을 설명합니다.
3.1 MySQL 데이터베이스에 연결하기
mysql-connector-python을 사용하여 MySQL에 연결하는 기본 예제 코드는 다음과 같습니다.
import mysql.connector
# Connection information for the MySQL server
conn = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='test_db'
)
# Verify the connection
if conn.is_connected():
print("Successfully connected to the MySQL server!")
이 코드에서는 mysql.connector.connect() 함수를 사용하여 로컬 MySQL 서버에 연결합니다. 연결이 성공하면 확인 메시지가 표시됩니다.
3.2 연결 실패 문제 해결
연결에 실패하면 다음과 같은 유형의 오류가 발생할 수 있습니다.
- Authentication error : 사용자 이름이나 비밀번호가 올바르지 않을 수 있습니다.
- Host connection error : 서버가 정상적으로 실행 중인지 확인하고 방화벽 설정을 검토하십시오.
프로그램이 예기치 않게 종료되는 것을 방지하려면 try-except 구문을 사용하여 오류를 처리할 수 있습니다.
try:
conn = mysql.connector.connect(...)
except mysql.connector.Error as err:
print(f"Error: {err}")
4. 기본 SQL 작업
MySQL에 성공적으로 연결되면 기본 SQL 작업을 수행할 수 있습니다. 이 섹션에서는 데이터를 삽입, 조회, 업데이트 및 삭제하는 방법을 설명합니다.
4.1 데이터 삽입
테이블에 새 데이터를 삽입하려면 다음과 같은 SQL 문을 사용합니다.
cursor = conn.cursor()
# Insert data query
insert_query = "INSERT INTO users (username, email) VALUES (%s, %s)"
data = ("user1", "user1@example.com")
# Execute the query
cursor.execute(insert_query, data)
# Commit the changes
conn.commit()
4.2 데이터 조회
데이터를 조회하려면 SELECT 문을 사용합니다. 아래 예시는 모든 사용자 레코드를 조회합니다.
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
# Display the results
for row in rows:
print(row)
4.3 데이터 업데이트
기존 데이터를 업데이트하려면 UPDATE 문을 사용합니다.
update_query = "UPDATE users SET email = %s WHERE username = %s"
cursor.execute(update_query, ("new_email@example.com", "user1"))
conn.commit()
4.4 데이터 삭제
불필요한 데이터를 제거하려면 DELETE 문을 사용합니다.
delete_query = "DELETE FROM users WHERE username = %s"
cursor.execute(delete_query, ("user1",))
conn.commit()

5. 고급 작업
다음에서는 트랜잭션 관리와 준비된 문과 같은 보다 고급 작업에 대해 설명합니다.
5.1 트랜잭션 관리
여러 데이터베이스 작업을 하나의 단위로 실행하고 필요 시 롤백하려면 트랜잭션을 사용합니다.
try:
cursor.execute("...")
conn.commit() # Commit if completed successfully
except:
conn.rollback() # Roll back if an error occurs
5.2 준비된 문 사용
SQL 인젝션 공격을 방지하려면 준비된 문을 사용하는 것이 권장됩니다.
stmt = "SELECT * FROM users WHERE username = %s"
cursor.execute(stmt, ("user1",))
6. Python과 MySQL 활용 실전 예제
Python과 MySQL을 결합하면 다양한 실용 애플리케이션을 개발할 수 있습니다. 이 섹션에서는 구체적인 예시를 통해 Python과 MySQL을 사용하는 방법을 설명합니다.
6.1 사용자 관리 시스템 구축
사용자 관리 시스템은 Python과 MySQL으로 구축된 애플리케이션의 전형적인 예시입니다. 아래는 간단한 사용자 관리 시스템의 기본 설계입니다.
단계 1: 사용자 테이블 생성
먼저, SQL CREATE TABLE 문을 사용하여 사용자 정보를 저장할 테이블을 생성합니다.
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL
);
단계 2: 사용자 등록 기능 구현
다음으로, 새로운 사용자를 등록하는 기능을 구현합니다. 아래 Python 코드는 INSERT 문을 사용하여 사용자 정보를 데이터베이스에 삽입합니다.
import mysql.connector
# Connect to MySQL
conn = mysql.connector.connect(user='root', password='password', host='localhost', database='test_db')
cursor = conn.cursor()
# Insert new user data
insert_query = "INSERT INTO users (username, email, password) VALUES (%s, %s, %s)"
user_data = ("user123", "user123@example.com", "securepassword")
cursor.execute(insert_query, user_data)
# Commit the changes
conn.commit()
# Close the connection
cursor.close()
conn.close()
단계 3: 로그인 기능 구현
사용자가 로그인할 수 있는 기능을 추가합니다. 아래 예시는 SELECT 문을 사용하여 사용자가 존재하는지 확인합니다.
# Authentication during login
login_query = "SELECT * FROM users WHERE username = %s AND password = %s"
login_data = ("user123", "securepassword")
cursor.execute(login_query, login_data)
user = cursor.fetchone()
if user:
print("Login successful")
else:
print("Login failed")
6.2 데이터 분석을 위한 MySQL 활용
MySQL을 데이터 저장소로 활용하고 Python 데이터 분석 라이브러리와 결합하여 분석을 수행할 수 있습니다. 아래는 Python의 Pandas 라이브러리를 사용한 예시입니다.
단계 1: MySQL에서 데이터 조회
다음 예시는 MySQL에서 데이터를 조회하고 이를 Pandas DataFrame으로 변환하여 분석하는 방법을 보여줍니다.
import mysql.connector
import pandas as pd
# Connect to MySQL
conn = mysql.connector.connect(user='root', password='password', host='localhost', database='test_db')
cursor = conn.cursor()
# Retrieve data and convert to a Pandas DataFrame
query = "SELECT * FROM users"
cursor.execute(query)
rows = cursor.fetchall()
df = pd.DataFrame(rows, columns=['id', 'username', 'email', 'password'])
# Preview the data
print(df.head())
# Close the connection
cursor.close()
conn.close()
Step 2: Data Aggregation and Analysis
You can use Pandas to perform aggregation and analysis. For example, you can analyze the distribution of email domains among users.
# Count users by email domain
df['domain'] = df['email'].apply(lambda x: x.split('@')[1])
domain_count = df['domain'].value_counts()
print(domain_count)
As shown above, by using MySQL as a backend and combining it with analysis tools such as Pandas, you can process data effectively.
7. Summary and Next Steps
So far, we have covered the basics of database operations using Python and MySQL integration, including building a user management system as a practical example and performing data analysis. This technology is extremely powerful for building the foundation of web applications and data processing systems.
7.1 Further Steps
After learning the fundamentals explained in this article, we recommend moving on to the following steps.
- Integrate with Django or Flask : Use Python frameworks to build more advanced web applications.
- Database optimization : Learn about MySQL indexing and query optimization to improve database performance.
- Big data analysis : Process MySQL data with Python and work on building machine learning models or conducting large-scale data analysis.


