目录
[二、CRUD 全流程](#二、CRUD 全流程)
[五、SQLAlchemy(ORM 推荐)](#五、SQLAlchemy(ORM 推荐))
前言
在现代数据驱动的应用开发中,Python 与 MySQL 的组合因其简洁、高效、稳定而广受欢迎。无论是 Web 后端、数据分析还是自动化脚本,掌握 Python 操作 MySQL 的技能都至关重要。本文将带你从零开始,系统学习如何使用 Python 安全、高效地连接、查询和管理 MySQL 数据库。
一、环境配置
1. PyMySQL
pip install PyMySQL
2. 基本连接
python
import pymysql
# 创建数据库连接
connection = pymysql.connect(
host='localhost',
user='testuser',
password='test123',
database='TESTDB',
charset='utf8mb4', # 推荐使用 utf8mb4 支持 emoji
cursorclass=pymysql.cursors.DictCursor # 返回字典而非元组
)
try:
with connection.cursor() as cursor:
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()
print(f"Database version: {version['VERSION()']}")
finally:
connection.close()
建议: 使用
with语句自动管理游标,确保资源释放。
二、CRUD 全流程
1. 创建表(Create)
python
create_table_sql = """
CREATE TABLE IF NOT EXISTS EMPLOYEE (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50),
age INT,
sex CHAR(1),
income DECIMAL(10, 2)
)
"""
with connection.cursor() as cursor:
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
cursor.execute(create_table_sql)
connection.commit()
2. 插入数据(Insert)
python
insert_sql = """
INSERT INTO EMPLOYEE (first_name, last_name, age, sex, income)
VALUES (%s, %s, % s, %s, %s)
"""
with connection.cursor() as cursor:
cursor.execute(insert_sql, ('Mac', 'Mohan', 20, 'M', 2000.0))
connection.commit()
print(f"Inserted record ID: {cursor.lastrowid}")
注意(SQL注入风险):
# 危险!易受 SQL 注入攻击 cursor.execute(f"INSERT ... VALUES ({name}, {age})")
3. 查询数据(Read)
python
query_sql = "SELECT * FROM EMPLOYEE WHERE income > %s"
with connection.cursor() as cursor:
cursor.execute(query_sql, (1000,))
results = cursor.fetchall()
for row in results:
print(f"Name: {row['first_name']} {row['last_name']}, Income: {row['income']}")
fetchone():获取单条记录fetchall():获取所有记录fetchmany(n):获取 n 条记录
4. 更新数据(Update)
python
update_sql = "UPDATE EMPLOYEE SET age = age + 1 WHERE sex = %s"
with connection.cursor() as cursor:
cursor.execute(update_sql, ('M',))
connection.commit()
print(f"Updated {cursor.rowcount} rows")
5. 删除数据(Delete)
python
delete_sql = "DELETE FROM EMPLOYEE WHERE age > %s"
with connection.cursor() as cursor:
cursor.execute(delete_sql, (25,))
connection.commit()
print(f"Deleted {cursor.rowcount} rows")
三、事务管理:确保数据一致性
MySQL 的 InnoDB 引擎支持 ACID 事务。Python 中通过 commit() 和 rollback() 控制:
python
try:
with connection.cursor() as cursor:
# 转账操作
cursor.execute("UPDATE accounts SET balance = balance - 100 WHERE user = 'Alice'")
cursor.execute("UPDATE accounts SET balance = balance + 100 WHERE user = 'Bob'")
connection.commit() # 提交事务
except Exception as e:
connection.rollback() # 回滚
print(f"Transaction failed: {e}")
建议 :所有写操作(INSERT/UPDATE/DELETE)必须显式调用
commit()才会生效!
四、技巧与建议
1. 使用连接池提升性能(生产环境必备)
python
from dbutils.pooled_db import PooledDB
pool = PooledDB(
creator=pymysql,
maxconnections=10,
host='localhost',
user='testuser',
password='test123',
database='TESTDB'
)
# 从池中获取连接
conn = pool.connection()
# ... 执行操作 ...
conn.close() # 归还连接到池
2. 处理异常(Error Handling)
python
from pymysql import MySQLError, IntegrityError
try:
cursor.execute("...")
except IntegrityError as e:
print("数据完整性错误:", e)
except MySQLError as e:
print("数据库错误:", e)
3. 批量插入(Bulk Insert)
python
data = [
('Alice', 'Smith', 30, 'F', 5000.0),
('Bob', 'Johnson', 25, 'M', 4500.0)
]
with connection.cursor() as cursor:
cursor.executemany(insert_sql, data)
connection.commit()
五、SQLAlchemy(ORM 推荐)
对于复杂项目,建议使用 SQLAlchemy 这样的 ORM(对象关系映射)工具:
python
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
first_name = Column(String(50))
income = Column(Float)
engine = create_engine('mysql+pymysql://user:pwd@localhost/TESTDB')
Session = sessionmaker(bind=engine)
session = Session()
# 添加记录
emp = Employee(first_name='Charlie', income=6000.0)
session.add(emp)
session.commit()
**建议:**避免手写 SQL,代码更面向对象,易于维护。
六、安全与性能
- 永远使用参数化查询防止 SQL 注入
- 及时关闭连接避免资源泄漏
- 使用索引加速查询(尤其 WHERE、JOIN 字段)
- 避免 SELECT,只取所需字段
- 敏感信息不要硬编码,使用环境变量或配置文件
小结
掌握 Python 操作 MySQL,是迈向全栈开发或数据工程的重要一步。从基础的 PyMySQL 到高级的 SQLAlchemy,选择适合项目规模的工具,并始终遵循安全、高效、可维护的原则。
"好的数据库代码,不仅跑得快,更要守得住安全底线。"
现在,就去连接你的第一个数据库吧!