python - 光标: AttributeError: 'NoneType' object has no attribute 'fetchall'

标签 python mysql attributeerror mysql-connector database-cursor

代码

对于游标查询:

import mysql.connector
from mysql.connector import errorcode

config = {
    'user': 'root',
    'password': 'root',
    'host': 'localhost',
    'database': 'myDatabase'}


cn = mysql.connector.connect(**config)
cur = cn.cursor()
emailExist = cur.execute("""SELECT * FROM customerDetails""").fetchall()
print(emailExist)

我的数据库文件与此脚本位于同一目录中。

属性错误

我收到此错误:

>>> emailExist = cur.execute("""SELECT * FROM customerDetails""").fetchall()

>>> AttributeError: 'NoneType' object has no attribute 'fetchall'

预期

当我在 MySQLWorkbench 中运行相同的查询时,输出为:

0 row(s) returned

最佳答案

查看文档 MySQL :: MySQL Connector/Python Developer Guide :: 10.5.6 MySQLCursor.fetchall() Method .

问题

错误消息

AttributeError: 'NoneType' object has no attribute 'fetchall'

对于声明

cur.execute("""SELECT * FROM customerDetails""")

内容为:

  • 执行语句返回None
  • 并且 None 的返回值没有 fetchall 属性或方法

修复

按以下顺序执行游标方法:

  1. cur.execute(sql) 创建游标(在 cur 中,而不是返回)
  2. cur.fetchall() 返回结果

关于python - 光标: AttributeError: 'NoneType' object has no attribute 'fetchall' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59829195/

相关文章:

Python3 PyQt5 setEnabled 的 QAction 导致崩溃

python - 裁剪图像的顶部 numpy (或 scipy)

php - 在 PHP 和 mySQL 中更改用户密码

php - 在与另一个表进行检查后,如何将单词插入到表中?

python - 将 PNG 图像编码为 Base64 时出现 AttributeError

python - 无法通过命令行 Python 安装 googlemaps api (Windows 8)

MySQL LEFT JOIN 与 SUBQUERY 非常慢

python - AttributeError,我在这里做错了什么?

python - 获取属性错误: module 'mod_commands' has no attribute 'ban' - even though I added it

python - 在 Python 中使用索引迭代列表