pyMySQL:如何检查连接是否已经打开或clos

2024-04-27 03:42:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了错误InterfaceError (0, '')。有没有办法在Pymysql库中检查连接或光标是否关闭。对于cursor,我已经在使用这样的上下文管理器:

with db_connection.cursor() as cursor:
  ....

Tags: 管理器dbas错误withconnectioncursorpymysql
3条回答

在if语句中使用conn.connection。

import pymysql

def conn():
    mydb=pymysql.Connect('localhost','root','password','demo_db',autocommit=True)
    return mydb.cursor()

def db_exe(query,c):
    try:
        if c.connection:
            print("connection exists")
            c.execute(query)
            return c.fetchall()
        else:
            print("trying to reconnect")
            c=conn()
    except Exception as e:
        return str(e)

dbc=conn()
print(db_exe("select * from users",dbc))

可以使用Connection.open属性。

如果连接打开,则Connection.open字段为1,否则为0。所以你可以说

if conn.open:
    # do something

The conn.open attribute will tell you whether the connection has been explicitly closed or whether a remote close has been detected. However, it's always possible that you will try to issue a query and suddenly the connection is found to have given out - there is no way to detect this ahead of time (indeed, it might happen during the process of issuing the query), so the only truly safe thing is to wrap your calls in a try/except block

我认为try-and-catch可能会成功,而不是只检查游标。

try:
   c = db_connection.cursor()
except OperationalError:
   connected = False
else:
   connected = True
   #code here

相关问题 更多 >