简体   繁体   English

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

[英]Check if a database connection is busy using python

I want to create a Database class which can create cursors on demand. 我想创建一个数据库类,该类可以按需创建游标。 It must be possible to use the cursors in parallel (two or more cursor can coexist) and, since we can only have one cursor per connection, the Database class must handle multiple connections. 必须可以并行使用游标(两个或多个游标可以共存),并且由于每个连接只能有一个游标,因此Database类必须处理多个连接。

For performance reasons we want to reuse connections as much as possible and avoid creating a new connection every time a cursor is created: whenever a request is made the class will try to find, among the opened connections, the first non-busy connection and use it. 出于性能方面的考虑,我们希望尽可能地重用连接,并避免在每次创建游标时都创建新的连接:每当发出请求时,该类都会尝试在打开的连接中查找第一个非繁忙的连接并使用它。

A connection is still busy as long as the cursor has not been consumed. 只要没有消耗游标,连接仍然很忙。

Here is an example of such 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

However looking at the PEP 249 standard I cannot find any way to check whether a connection is actually being used or not. 但是,在查看PEP 249标准时,我找不到任何方法来检查连接是否正在实际使用。

Some implementations such as MySQL Connector offer ways to check whether a connection has still unread content (see here ), however as far as I know those are not part of PEP 249. 诸如MySQL Connector之类的某些实现提供了检查连接是否仍未读取内容的方法(请参阅此处 ),但是据我所知,这些都不属于PEP 249。

Is there a way I can achieve what described before for any PEP 249 compliant python database API ? 有没有一种方法可以实现任何符合PEP 249的python数据库API的描述?

Perhaps you could use the status of the cursor to tell you if a cursor is being used. 也许您可以使用游标的状态来告诉您是否正在使用游标。 Let's say you had the following cursor: 假设您有以下游标:

new_cursor = new_connection.cursor()
cursor.execute(new_query)

and you wanted to see if that connection was available for another cursor to use. 并且您想查看该连接是否可供其他游标使用。 You might be able to do something like: 可能可以执行以下操作:

if (new_cursor.rowcount == -1):
    another_new_cursor = new_connection.cursor()
    ...

Of course, all this really tells you is that the cursor hasn't executed anything yet since the last time it was closed. 当然,这实际上告诉您的是,自上次关闭游标以来,游标尚未执行任何操作。 It could point to a cursor that is done (and therefore a connection that has been closed) or it could point to a cursor that has just been created or attached to a connection. 它可以指向完成的游标(并因此指向已关闭的连接),也可以指向刚刚创建或附加到连接的游标。 Another option is to use a try/catch loop, something along the lines of: 另一种选择是使用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.")

Of course, you probably don't want to be spammed with printed messages but you can do whatever you want in that except block, sleep for 5 seconds, wait for some other variable to be passed, wait for user input, etc. If you are restricted to PEP 249, you are going to have to do a lot of things from scratch. 当然,您可能不希望被打印的消息所淹没,但是您可以在该块中做任何您想做的事情,除了块,休眠5秒,等待其他变量传递,等待用户输入等。如果仅限于PEP 249,您将不得不从头开始做很多事情。 Is there a reason you can't use external libraries? 您有理由不能使用外部库吗?

EDIT: If you are willing to move outside of PEP 249, here is something that might work, but it may not be suitable for your purposes. 编辑:如果您愿意搬到PEP 249之外,这可能会起作用,但它可能不适合您的目的。 If you make use of the mysql python library, you can take advantage of the is_connected method. 如果您使用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()
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM