You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Python连接MySQL 5.1遇驱动兼容问题,求成功方案

解决MySQL 5.1与Python连接的可行方案

方案1:使用pymysql指定旧认证插件

MySQL 5.1默认采用mysql_native_password认证插件,部分新版本pymysql可能默认使用新插件导致连接失败。你可以安装适配旧版MySQL的pymysql版本(比如0.9.3),并在连接时显式指定认证方式。

安装命令:

pip install pymysql==0.9.3

连接代码示例:

import pymysql

conn = pymysql.connect(
    host='你的主机地址',
    user='用户名',
    password='密码',
    database='目标数据库',
    auth_plugin='mysql_native_password',
    charset='utf8'
)

# 测试连接
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
print(cursor.fetchone())
cursor.close()
conn.close()

方案2:使用适配的MySQLdb版本

PySQLdb(即MySQLdb)的新版本不再支持MySQL 5.1,你可以尝试安装对应兼容版本:

  • Python 2.7环境:安装MySQL-python==1.2.5
  • Python 3.x环境:安装mysqlclient==1.4.6(它是MySQLdb的分支,适配Python3)

安装命令(以Python3为例):

pip install mysqlclient==1.4.6

连接代码示例:

import MySQLdb

conn = MySQLdb.connect(
    host='你的主机地址',
    user='用户名',
    passwd='密码',
    db='目标数据库',
    charset='utf8'
)

cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
print(cursor.fetchone())
cursor.close()
conn.close()

方案3:修正Oracle Connector/Python在Python2.7的使用问题

你遇到的super()错误,是因为代码用了Python3的super()语法(如super().__init__()),而Python2.7需要显式传入类和实例参数(super(类名, self).__init__())。配合适配的Connector/Python版本(1.2.3)即可解决。

安装命令:

pip install mysql-connector-python==1.2.3

兼容Python2.7的连接代码示例:

import mysql.connector

class CustomConnection(mysql.connector.MySQLConnection):
    def __init__(self, **kwargs):
        super(CustomConnection, self).__init__(**kwargs)

conn = CustomConnection(
    host='你的主机地址',
    user='用户名',
    password='密码',
    database='目标数据库'
)

cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
print(cursor.fetchone())
cursor.close()
conn.close()

成功连接的常见案例

不少开发者通过以下方式成功连接MySQL5.1:

  • Python3.7+环境下,用pymysql 0.9.3版本并指定auth_plugin='mysql_native_password'
  • Python2.7环境下,使用MySQL-python 1.2.5,或修正super()语法后的Connector/Python 1.2.3
  • 有数据库管理员权限的用户,通过执行ALTER USER 'user'@'host' IDENTIFIED WITH mysql_native_password BY 'password';重置用户认证方式,解决了"Access denied"报错

内容的提问来源于stack exchange,提问作者Roger Irwin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 11:47:42