Search code examples
pythonmysql-connector-python

Can a MySQL connector be shared between objects?


I'm using MySQL Connector/Python. I have an object that generates objects, and some of those objects generate more objects. At the moment, I'm ending up with around 300 total objects. Given the way I have it set up, that means 300 database connections. Is it possible to connect once and simply pass the connection around?

I envision it looking something like this:

class MyObject(dict):
    def __init__(self, row, conn):
        self.conn = conn
        self.cursor = self.conn.cursor()
        # pass the connection/cursor on to some more objects

def getObjects(query, args):
    conn = mysql.connector.connect(user="user", password="password", host="localhost", port="12345", database="database")
    cursor = conn.cursor()
    cursor.execute(query, args)
    row = cursor.fetchone()

    myObjects = []
    while rowDict is not None:
        myObj = MyObject(row, conn)
        myObjects.append(myObj)
        row = cursor.fetchone()

    cursor.close()
    conn.close()

    return myObjects

But when I implement it in this way, I get InternalError: Unread result found..


Solution

  • Well I think the answer is: use pools. Once I implemented connection pooling, I got my connections down from 300 to 10. It basically looks like this:

    def getConnectionPool():
        config = {
                    "user":"user", 
                    "password":"password", 
                    "host":"localhost", 
                    "port":"12345", 
                    "database":"database"
                  }
        pool = mysql.connector.pooling.MySQLConnectionPool(pool_name="MyPool", pool_size=10, **config)
        return pool
    
    def getAllObjects():
        pool = getConnectionPool()
        newObject = NewObject(pool)
    
    class NewObject(object):
        def __init__(self, pool):
            self.conn = pool.get_connection()
            # cursor, etc.