使用 python 检查数据库连接是否正忙

Check if a database connection is busy using python

我想创建一个可以按需创建游标的数据库class。 必须可以并行使用游标(两个或多个游标可以共存),并且由于每个连接只能有一个游标,数据库 class 必须处理多个连接。

出于性能原因,我们希望尽可能重用连接并避免每次创建游标时都创建新连接: 每当发出请求时,class 将尝试在打开的连接中找到第一个非繁忙连接并使用它。

只要游标还没有被消耗,连接就仍然繁忙。

这里有一个这样的例子 class:

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()
    ...