Subclassing mysql.connector

Any idea why I can’t subclass mysql.connector like this:

import mysql.connector

class Database(mysql.connector.MySQLConnection):
    def __init__(self, *args, **kwargs):
        super().__init__(**kwargs)

db_config={'host':'...', 'database':'...', 'user':'...', 'passwd':'...', 'autocommit':True}
db = Database(**db_config)
db_conn = db.connect(**db_config)
print(db_conn)
oCursor = db_conn.cursor() # <- this fails with 'NoneType' object has no attribute 'cursor'

oCursor.execute("SELECT 1")
db_conn.close()

If this is the documentation for the library you’re using, it looks like the connect() function doesn’t return a value. Does this work?

db = Database(**db_config)
db.connect(**db_config)
oCursor = db.cursor()

Still get AttributeError: 'NoneType' object has no attribute 'cursor'.

Really? Can you show the updated code and which line is failing?

import mysql.connector
class Database(mysql.connector.MySQLConnection):
        def __init__(self, *args, **kwargs):
            super().__init__(**kwargs)

db_config={'host':'...', 'database':'...', 'user':'...', 'passwd':'...'}

db = Database(**db_config)
db.connect(**db_config)
oCursor = db.cursor() # <- this fails with 'NoneType' object has no attribute 'cursor'

According to the source, instantiating the superclass with keyword arguments already creates the connection, so there is no need to call db.connect afterwards. Since the call to connect could not have modified the global to set db to None, some attribute of the db object must have been set to None instead to cause the error. Can you paste the traceback here?

Well I’ll be …

It is now working correctly but I don’t know why. Yesterday I copied that code back and forth to check it was correct and it always fell over with the NoneType error, however today all is working fine. I wonder if I did something within PyCharm to update mysql.connector.python or something like that.

Either way many thanks for the help @duncathan and @jonathandung, latest working code below:

import mysql.connector
class Database(mysql.connector.MySQLConnection):
    def __init__(self, *args, **kwargs):
        super().__init__(**kwargs)
    def runSQL(self, sql):
        print(self.is_connected())
        with self.cursor() as oCursor:
            oCursor.execute(sql)
            data = oCursor.fetchall()
            return data

db_config={'host':'...', 'database':'...', 'user':'...', 'passwd':'...'}

db = Database(**db_config)
print(db.runSQL("SELECT 1"))
db.close()