Search code examples
pythonattributeerrormysql-connectordatabase-cursor

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


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

Solution

  • 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.