在Python中,如何使用MySQLdb模块连接MySQL数据库?
你想了解如何使用 MySQLdb 模块在 Python 中连接 MySQL 数据库,这是 Python 操作 MySQL 的经典模块(主要适用于 Python 2,Python 3 常用 mysqlclient 作为替代),我会完整讲解安装、连接、基础操作的方法。
一、前置说明
MySQLdb 本身是 Python 2 的库,Python 3 中官方维护的替代版本是 mysqlclient(本质是 MySQLdb 的 Python 3 兼容版,导入时仍用 import MySQLdb),因此先明确安装方式:
1. 安装依赖(区分系统)
# Windows(直接安装)
pip install mysqlclient
# Linux(先装系统依赖,再装python库)
# Ubuntu/Debian
sudo apt-get install libmysqlclient-dev python3-dev
pip install mysqlclient
# CentOS/RHEL
sudo yum install mysql-devel python3-devel
pip install mysqlclient
二、完整连接与操作示例
下面是使用 MySQLdb 连接 MySQL、执行 SQL、调用存储过程的完整代码:
import MySQLdb
from MySQLdb import Error
def connect_mysql_with_mysqldb():
# 数据库连接配置
db_config = {
'host': 'localhost', # 数据库地址
'user': 'root', # 用户名
'password': '你的数据库密码', # 密码
'database': 'test_db', # 数据库名
'charset': 'utf8mb4' # 字符集(避免中文乱码)
}
# 初始化连接和游标
connection = None
cursor = None
try:
# ========== 1. 建立数据库连接 ==========
connection = MySQLdb.connect(**db_config)
print("数据库连接成功!")
# ========== 2. 创建游标(用于执行SQL) ==========
# cursorclass=MySQLdb.cursors.DictCursor:返回字典格式的结果(默认是元组)
cursor = connection.cursor(cursorclass=MySQLdb.cursors.DictCursor)
# ========== 3. 执行基础SQL操作(示例:查询) ==========
# 执行查询SQL
cursor.execute("SELECT * FROM users WHERE id = %s", (1,)) # 参数化查询,避免SQL注入
# 获取单条结果
user = cursor.fetchone()
print("\n查询单条用户数据:")
print(f"ID: {user['id']}, 姓名: {user['name']}, 年龄: {user['age']}")
# ========== 4. 调用存储过程(重点) ==========
print("\n调用存储过程(get_user_by_id):")
# 方式1:直接执行CALL语句(MySQLdb无专门的callproc方法,用EXECUTE执行CALL)
user_id = 2
# 调用带OUT参数的存储过程:@变量名接收OUT参数
cursor.execute("CALL get_user_by_id(%s, @user_name, @user_age)", (user_id,))
# 查询OUT参数的值
cursor.execute("SELECT @user_name AS name, @user_age AS age")
result = cursor.fetchone()
print(f"ID={user_id}的用户:姓名={result['name']}, 年龄={result['age']}")
# 方式2:调用无参数存储过程(返回结果集)
print("\n调用无参数存储过程(get_all_users):")
cursor.execute("CALL get_all_users()")
# 获取所有结果
all_users = cursor.fetchall()
for user in all_users:
print(f"ID: {user['id']}, 姓名: {user['name']}, 邮箱: {user['email']}")
# ========== 5. 执行增删改操作(需提交事务) ==========
# 示例:插入数据
# cursor.execute("INSERT INTO users (name, age, email) VALUES (%s, %s, %s)",
# ("王五", 28, "wangwu@test.com"))
# connection.commit() # 增删改必须提交事务
except Error as e:
print(f"数据库操作出错:{e}")
# 出错时回滚事务
if connection:
connection.rollback()
finally:
# ========== 6. 关闭资源 ==========
if cursor:
cursor.close()
if connection:
connection.close()
print("\n数据库连接已关闭")
if __name__ == "__main__":
connect_mysql_with_mysqldb()
三、关键知识点解释
1. 核心连接方法
MySQLdb.connect() 的关键参数:
host:数据库服务器地址(本地用localhost)user/password:数据库账号密码database:要连接的数据库名charset:字符集(推荐utf8mb4,支持所有中文和emoji)port:端口号(默认3306,可省略)
2. 游标(Cursor)的使用
- 普通游标:默认返回元组格式(如
(1, '张三', 25)) - 字典游标:
cursorclass=MySQLdb.cursors.DictCursor,返回字典格式(如{'id':1, 'name':'张三', 'age':25}),更易读 - 核心方法:
execute(sql, params):执行单条SQL,params是参数元组(避免SQL注入)fetchone():获取一条结果fetchall():获取所有结果fetchmany(n):获取n条结果
3. 调用存储过程的特殊处理
MySQLdb 不像 mysql-connector-python 有专门的 callproc 方法,需通过执行 CALL 语句实现:
- 带OUT参数:用 MySQL 会话变量(
@变量名)接收 OUT 参数,再通过SELECT @变量名获取值 - 无参数/仅IN参数:直接执行
CALL 存储过程名(参数)即可
4. 事务处理
- 增删改操作(INSERT/UPDATE/DELETE)必须调用
connection.commit()提交事务 - 出错时调用
connection.rollback()回滚,避免数据不一致

浙公网安备 33010602011771号