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

Python连接MySQL触发0xC0000005(访问违例)崩溃问题

问题:Python连接MySQL时触发0xC0000005访问违例错误

我在全新安装的Windows 11虚拟机中部署了MySQL和PyCharm,编写测试代码验证Python与MySQL的连通性,但调用mysql.connector.connect()时程序直接崩溃,返回退出码-1073741819 (0xC0000005)(访问违例错误)。

初始测试代码

print('Start mySQL Query test')
import mysql.connector
print('Test')

cnx = mysql.connector.connect(user='python', password='password!', host='127.0.0.1', database='mes_core')
print('Test2') # 这行永远不会打印,因为connect调用崩溃了

try:
    cursor = cnx.cursor()
    cursor.execute('select * from enterprise')
    result = cursor.fetchall()
    print(f'result={result}')
finally:
    cnx.close()

报错信息

Process finished with exit code -1073741819 (0xC0000005)

版本信息

  • Python mysql.connector版本:9.2.0
  • MySQL Workbench版本:8.0.40
  • 系统:Windows 11(全新虚拟机安装)

调试尝试

我将connect调用包裹在try块中调试,但程序仍在connect调用处崩溃,完全无法进入异常处理逻辑:

import mysql.connector
from mysql.connector import errorcode

try:
  print('About to connect')
  cnx = mysql.connector.connect(user='python',
                                password='Bootcamp',
                                host='127.0.0.1',
                                database='mes_core')
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("用户名或密码有误")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("数据库不存在")
  else:
    print(err)
else:
  print('连接成功')
  cnx.close()

调试输出

About to connect

Process finished with exit code -1073741819 (0xC0000005)

解决思路与方案

这个错误是因为mysql-connector-python 9.x版本在Windows环境下和MySQL 8.0.40存在底层兼容性问题,属于C扩展库的内存访问错误,Python的try-except无法捕获这类底层崩溃。可以按以下步骤解决:

  1. 降级mysql-connector-python版本
    卸载当前9.2.0版本,安装8.0.33或更早的稳定版本:

    pip uninstall mysql-connector-python
    pip install mysql-connector-python==8.0.33
    
  2. 确认MySQL服务状态
    确保本地MySQL服务已启动,打开命令提示符执行:

    net start mysql
    

    若服务未启动,先启动服务再测试连接。

  3. 检查数据库用户权限
    确认python用户拥有访问mes_core数据库的权限,在MySQL Workbench中执行:

    GRANT ALL PRIVILEGES ON mes_core.* TO 'python'@'127.0.0.1';
    FLUSH PRIVILEGES;
    
  4. 强制使用纯Python模式连接
    若降级版本后仍有问题,可强制mysql.connector使用纯Python实现(不依赖C扩展),修改连接代码:

    cnx = mysql.connector.connect(
        user='python',
        password='password!',
        host='127.0.0.1',
        database='mes_core',
        use_pure=True
    )
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 06:28:21