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

Question:

I tried to return the result of an SQL query.

This works perfectly with pyodbc but not with mysql-connector.

Error Output

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

Code

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
Asked By: PyDeveloper

||

Answers:

Try this code.
If you are still having problems check that the connection to the database is successful.

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
Answered By: Marco Gatto

PEP 249, the DBAPI spec, says that the return value of execute is undefined. Quite a few DBAPI implementations return None, meaning that you cannot (portably) chain execute().fetchall() as you are trying to do.

Answered By: Ture Pålsson