我想创建一个可以按需创建游标的Database类。必须可以并行使用游标(两个或多个游标可以共存),并且由于每个连接只能有一个游标,因此Database类必须处理多个连接。
出于性能原因,我们希望尽可能多地重用连接,并避免在每次创建游标时创建新连接:每当发出请求时,类将尝试在打开的连接中查找第一个非繁忙连接并使用它。
只要光标尚未消耗,连接仍然很忙。
以下是此类的示例:
class Database:
...
def get_cursos(self,query):
selected_connection = None
# Find usable connection
for con in self.connections:
if con.is_busy() == False: # <--- This is not PEP 249
selected_connection = con
break
# If all connections are busy, create a new one
if (selected_connection is None):
selected_connection = self._new_connection()
self.connections.append(selected_connection)
# Return cursor on query
cur = selected_connection.cursor()
cur.execute(query)
return cur
然而,看看PEP 249标准,我找不到任何方法来检查连接是否实际被使用。
某些实现(如MySQL Connector)提供了检查连接是否仍有未读内容的方法(请参阅here),但据我所知,这些不是PEP 249的一部分。
有没有办法可以实现任何符合PEP 249标准的python数据库API的描述?
也许您可以使用光标的状态来告诉您是否正在使用光标。假设您有以下光标:
new_cursor = new_connection.cursor()
cursor.execute(new_query)
并且您想要查看该连接是否可用于其他游标。你可以做类似的事情:
if (new_cursor.rowcount == -1):
another_new_cursor = new_connection.cursor()
...
当然,所有这些都告诉你,自从上次关闭游标以来,游标还没有执行任何操作。它可以指向已完成的游标(因此已关闭的连接),或者它可能指向刚刚创建或附加到连接的游标。另一种选择是使用try / catch循环,类似于:
try:
another_new_cursor = new_connection.cursor()
except ConnectionError?: //not actually sure which error would go here but you get the idea.
print("this connection is busy.")
当然,您可能不希望被打印的邮件发送垃圾邮件,但除了阻止,你可以做任何你想做的事情,睡5秒,等待其他变量通过,等待用户输入等等。如果你仅限于PEP 249,您将不得不从头开始做很多事情。有没有理由不能使用外部库?
编辑:如果你愿意离开PEP 249,这可能有用,但它可能不适合你的目的。如果你使用mysql
python库,你可以利用is_connected
方法。
new_connection = mysql.connector.connect(host='myhost',
database='myDB',
user='me',
password='myPassword')
...stuff happens...
if (new_connection.is_connected()):
pass
else:
another_new_cursor = new_connection.cursor()
...