返回的Python SQL查询'NoneType'对象

时间:2020-01-20 18:41:28

标签: python mysql sql python-3.x

我有以下用于查询的python代码:

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”对象没有属性“ fetchall”

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

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

返回了0行

添加了插入代码:

cursor = cn.cursor()
sql1 = """INSERT INTO customerDetails
VALUES (3, "h", "h",
"h", "h", "h",
"h", "h", "h",
1, 1, 1)"""
result = cursor.execute(sql1)
cursor.close()
cn.close()

1 个答案:

答案 0 :(得分:1)

文档:https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchall.html

AttributeError:“ NoneType”对象没有属性“ fetchall”

意思是:

cur.execute("""SELECT * FROM customerDetails""")返回None,并且没有fetchall属性。

您必须在光标(cur.fetchall())上使用fetchall()方法。