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

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

我试图制作一个简短的语句函数,它将 return 给我查询结果。 这适用于 pyodbc,但不适用于 mysql 连接器。

输出是:

File "/mySQLDB.py", line 17, in execute_and_fetch result = conn.cursor().execute(query, params).fetchall() AttributeError: 'NoneType' object has no attribute 'fetchall'

import mysql.connector

class MYSQLDB:
    def __init__(self):
        self.host = 'xx'
        self.database = 'xx$xx'
        self.user = 'xx'
        self.password = 'xx'

    def execute(self, query, *params):
        mysql.connector.connect(host=self.host, database=self.database,
                         user=self.user, password=self.password).cursor().execute(query, params).commit()

    def execute_and_fetch(self, query, *params):
        conn = mysql.connector.connect(host=self.host, database=self.database,
                         user=self.user, password=self.password)
        result = conn.cursor().execute(query, params).fetchall()
        conn.commit()
        return result

试试这个代码。 如果您仍然遇到问题,请检查与数据库的连接是否成功。

import mysql.connector

class MYSQLDB:
    def __init__(self):
        self.host = 'xx'
        self.database = 'xx$xx'
        self.user = 'xx'
        self.password = 'xx'

    def execute(self, query, *params):
        mysql.connector.connect(host=self.host, database=self.database,
                         user=self.user, password=self.password).cursor().execute(query, params).commit()

    def execute_and_fetch(self, query, *params):
        conn = mysql.connector.connect(host=self.host, database=self.database,
                         user=self.user, password=self.password)
        
        with conn.cursor() as cursor:

            cursor.execute(query, params=None)
...         result = cursor.fetchall()
            conn.commit()
            return result

PEP 249, the DBAPI spec,表示 execute 的 return 值未定义。相当多的 DBAPI 实现 return None,这意味着您不能(可移植地)链接 execute().fetchall(),就像您尝试做的那样。