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

mysql.connector报错AttributeError:无cursor_cext属性的问题求助

解决AttributeError: module 'mysql.connector' has no attribute 'cursor_cext'

问题根源

你的错误出在create_db函数的返回类型注解上:

  • mysql.connector.cursor_cext并非顶层模块直接可访问的子模块,必须显式导入
  • 类型注解里你写了CMySQLCursor(),这是创建实例的写法,类型注解应该用类本身CMySQLCursor
  • 另外check_dbases的返回类型标注是tuple,但实际返回的是列表,也需要修正

修复步骤

  1. 显式导入CMySQLCursor类型
  2. 修正函数的返回类型注解
  3. (可选)如果环境未安装带C扩展的连接器,需安装对应包

修改后的代码

import mysql.connector
from mysql.connector.cursor_cext import CMySQLCursor  # 显式导入C扩展游标类型

def create_db(name: str) -> CMySQLCursor:  # 去掉括号,用类型本身
    """此函数用于创建名为name的数据库"""
    # 步骤1:创建连接
    mydb = mysql.connector.connect(
        host="localhost",
        user="root",
        password="123456",
    )

    # 步骤2:创建数据库
    c = mydb.cursor()
    c.execute(f"CREATE DATABASE {name}")
    print(type(c))
    return c


def check_dbases() -> list[tuple]:  # 修正返回类型为列表套元组
    """此函数用于检查现有数据库"""
    mydb = mysql.connector.connect(
        host="localhost",
        user="root",
        password="123456",
    )

    cursor = mydb.cursor()
    cursor.execute("SHOW DATABASES")
    return [x for x in cursor]

额外说明

如果运行后仍提示找不到cursor_cext,说明你安装的是纯Python版本的mysql-connector-python,可以安装带C扩展的版本:

pip install mysql-connector-python-cext

或者改用默认的纯Python游标类型,修改导入和注解为:

from mysql.connector.cursor import MySQLCursor

def create_db(name: str) -> MySQLCursor:
    # ... 其余代码不变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:05:18