今天详细讲解一下在 Python 中连接 MySQL 数据库的几种主流方法。这将是一个从基础到进阶的完整指南。
在 Python 中连接 MySQL,主要有两个流行的驱动:
1. mysql-connector-python: MySQL 官方提供的纯 Python 驱动。无需其他依赖,安装简单。
2. PyMySQL: 一个纯 Python 的 MySQL 客户端,兼容性很好,非常流行。
3. (底层驱动) MySQLdb: 一个 C 扩展模块,速度很快,但在 Python 3 上安装可能较麻烦,通常被 PyMySQL 替代。
对于现代项目,PyMySQL 和 mysql-connector-python 是最常见的选择。本指南将以 `PyMySQL` 和 `SQLAlchemy` 为例。
方法一:使用 PyMySQL 直接连接(基础方法)
这种方式提供了最直接的 SQL 操作,适合需要完全控制 SQL 语句的场景。
完整的操作流程遵循 连接 -> 创建游标 -> 执行SQL -> 提交 -> 关闭 的步骤。
from pymysql.cursors import DictCursor 可选,用于获取字典格式的结果
connection = pymysql.connect(
host='localhost', 数据库服务器地址,本地可用 localhost 或 127.0.0.1
user='your_username', 用户名
password='your_password', 密码
database='your_database_name', 要连接的数据库名
charset='utf8mb4', 字符集,支持中文和表情符号推荐 utf8mb4
cursorclass=DictCursor 可选:设置游标类型,返回字典而非元组
with connection.cursor() as cursor:
sql = "SELECT `id`, `name` FROM `users` WHERE `email` = %s"
cursor.execute(sql, ('user@example.com',)) 使用参数化查询,防止SQL注入!
result = cursor.fetchone() 获取单条记录
print(result) 如果是DictCursor,输出: {'id': 1, 'name': 'John'}
results = cursor.fetchall()
with connection.cursor() as cursor:
sql = "INSERT INTO `users` (`name`, `email`) VALUES (%s, %s)"
cursor.execute(sql, ('Alice', 'alice@example.com'))
3. 提交事务!对于INSERT/UPDATE/DELETE等写操作,必须提交才会生效。
with connection.cursor() as cursor:
sql = "INSERT INTO `users` (`name`, `email`) VALUES (%s, %s)"
cursor.execute(sql, ('Bob', 'bob@example.com'))
print(f"新插入记录的ID是: {cursor.lastrowid}")
为了确保连接总是能被正确关闭,即使发生异常,推荐使用 `with` 语句。
with pymysql.connect(host='localhost', user='root', password='password', database='test') as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT VERSION()")
result = cursor.fetchone()
print(f"Database version: {result[0]}")
连接结束时,如果没有异常,会自动 commit(); 如果有异常,会自动 rollback()
except pymysql.Error as e:
print(f"Database error: {e}")
方法二:使用 SQLAlchemy (ORM 框架,进阶方法)
ORM (Object-Relational Mapping) 允许你使用 Python 类和对象来操作数据库,而不是直接写 SQL。这对于大型、复杂的项目非常有益,可以提高开发效率和代码可维护性。
pip install sqlalchemy pymysql
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
格式: dialect+driver://username:password@host:port/database
DB_URI = 'mysql+pymysql://username:password@localhost:3306/your_database?charset=utf8mb4'
2. 创建引擎 (Engine),它是ORM和数据库的连接核心
engine = create_engine(DB_URI, echo=True) echo=True 会打印执行的SQL,调试时有用
Base = declarative_base()
__tablename__ = 'users' 指定映射的表名
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(50), nullable=False)
email = Column(String(100), unique=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
with Session() as session:
new_user = User(name='Charlie', email='charlie@example.com')
print(f"New user ID: {new_user.id}") 提交后,id自动赋值
with Session() as session:
users = session.query(User).all()
print(user.id, user.name, user.email)
user = session.query(User).filter_by(name='Charlie').first()
print(f"Found user: {user.name}")
错误做法(SQL注入风险): `cursor.execute(f"SELECT * FROM users WHERE name = '{user_input}'")`
正确做法: `cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))`
PyMySQL 使用 `%s` 作为占位符,即使数据是数字或日期。
使用环境变量或配置文件(如 `.env` 文件)来管理。
pip install python-dotenv
DB_PASSWORD=your_secure_password
from dotenv import load_dotenv
load_dotenv() 加载 .env 文件中的环境变量
connection = pymysql.connect(
host=os.getenv('DB_HOST'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
database=os.getenv('DB_NAME')
数据库连接是昂贵的资源,一定要确保在使用后正确关闭。强烈推荐使用 `with` 语句上下文管理器。
简单脚本、需要精细控制SQL:选择 PyMySQL 或 mysql-connector-python。
Web应用、复杂业务逻辑、希望代码更Pythonic:选择 SQLAlchemy ORM。
另外搭配便捷的MYSQL备份工具,可定时备份、异地备份,MYSQL导出导入。可本地连接LINUX里的MYSQL,简单便捷。可以大大地提高工作效率喔。