我想要创建一个数据库类,它可以根据需要创建游标。必须可以并行使用游标(两个或多个游标可以共存),而且由于每个连接只能有一个游标,所以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然而,看看佩普249标准,我找不到任何方法来检查是否实际使用了连接。
有些实现,如MySQL连接器,提供了检查连接是否仍有未读内容的方法(请参阅这里),但据我所知,这些内容不是PEP 249的一部分。
是否有一种方法可以实现前面描述的任何PEP 249兼容python数据库API?
发布于 2019-03-19 16:16:08
也许您可以使用游标的状态来告诉您是否正在使用游标。假设您有以下游标:
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()
...https://stackoverflow.com/questions/55244737
复制相似问题