目录
Python连接MySQL:驱动库与ORM框架全面指南
摘要:本文详解Python操作MySQL的两种方式——原生驱动库与ORM框架,对比主流工具并提供实战代码示例,助你高效管理数据库!
一、为什么需要连接MySQL?
Python在数据分析、Web开发等领域广泛应用,而MySQL作为最流行的开源关系型数据库,其与Python的交互必不可少。操作方式主要分两类:
- 原生驱动库:直接执行SQL语句,灵活高效
- ORM框架:对象关系映射,用Python类操作数据库,提升开发效率
二、原生驱动库推荐及实战
1. mysql-connector-python(Oracle官方维护)
# 安装:pip install mysql-connector-python
import mysql.connector
config = {
"user": "root",
"password": "123456",
"host": "localhost",
"database": "test_db"
}
try:
conn = mysql.connector.connect(**config)
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE age > %s", (20,))
print(cursor.fetchall()) # 输出查询结果
except Exception as e:
print(f"Database error: {e}")
finally:
cursor.close()
conn.close()
2. PyMySQL(纯Python实现,兼容性好)
# 安装:pip install pymysql
import pymysql
conn = pymysql.connect(
host='localhost',
user='root',
password='123456',
database='test_db'
)
with conn.cursor() as cursor:
cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ('Alice', 25))
conn.commit() # 提交事务
三、ORM框架:用Python类操作数据库
1. SQLAlchemy(企业级首选)
# 安装:pip install sqlalchemy pymysql
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base, sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(30))
age = Column(Integer)
# 连接数据库(格式:mysql+pymysql://user:password@host/db)
engine = create_engine("mysql+pymysql://root:123456@localhost/test_db")
Base.metadata.create_all(engine) # 自动建表
# 操作数据
Session = sessionmaker(bind=engine)
session = Session()
new_user = User(name="Bob", age=30)
session.add(new_user)
session.commit()
# 查询数据
users = session.query(User).filter(User.age > 20).all()
2. Peewee(轻量级,适合快速开发)
# 安装:pip install peewee pymysql
from peewee import *
db = MySQLDatabase('test_db', user='root', password='123456', host='localhost')
class User(Model):
name = CharField()
age = IntegerField()
class Meta:
database = db
db.connect()
db.create_tables([User]) # 创建表
# 插入数据
User.create(name="Charlie", age=28)
# 查询数据
query = User.select().where(User.age > 25)
for user in query:
print(user.name, user.age)
3. Django ORM(Django项目内置)
# 在Django项目的models.py中定义
from django.db import models
class User(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
# 命令行生成迁移文件并执行
# python manage.py makemigrations
# python manage.py migrate
# 在视图函数中使用
users = User.objects.filter(age__gt=20)
四、对比总结:如何选择?
| 工具类型 | 代表库 | 适用场景 |
|---|---|---|
| 原生驱动 | PyMySQL | 需要精细控制SQL/高性能查询 |
| 全能ORM | SQLAlchemy | 大型项目/复杂事务处理 |
| 轻量ORM | Peewee | 快速原型开发/小型应用 |
| 全栈框架内置ORM | Django ORM | 使用Django开发Web应用 |
性能建议:高频写入场景用原生驱动,复杂业务逻辑用ORM提升可维护性。
五、常见问题解决方案
-
连接超时:
# 在connect参数中添加超时设置 conn = pymysql.connect(..., connect_timeout=10) -
中文乱码:
连接字符串添加编码参数:mysql+pymysql://root:123456@localhost/test_db?charset=utf8mb4 -
ORM批量插入优化:
# SQLAlchemy批量插入 session.bulk_save_objects([User(name=f"user{i}") for i in range(1000)]) session.commit()
结语:根据项目需求灵活选择工具,小型项目可用Peewee快速迭代,企业级系统推荐SQLAlchemy。掌握原生SQL与ORM的双重技能,才是Python工程师的终极武器!
技术栈扩展:
- 异步支持:aiomysql + SQLAlchemy 1.4+
- 数据库迁移:Alembic(配合SQLAlchemy)
- 连接池:SQLAlchemy自带连接池 / DBUtils
GitHub资源:
关键词:
Python MySQL、ORM框架、SQLAlchemy教程、PyMySQL示例、数据库连接
(完)
8万+

被折叠的 条评论
为什么被折叠?



