我正在使用MySQL Connector / Python。我有一个生成对象的对象,其中一些对象生成更多对象。目前,我最终得到了大约300个对象。鉴于我设置它的方式,这意味着300个数据库连接。是否可以连接一次并简单地通过连接?
我认为它看起来像这样:
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
但是当我以这种方式实现它时,我得到InternalError: Unread result found.
。
答案 0 :(得分:0)
我认为答案是:使用池。一旦我实现了连接池,我将连接从300减少到10.它基本上是这样的:
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.