繁体   English   中英

如何在python中检查mysql连接的状态?

[英]How to check the status of a mysql connection in python?

我正在使用 pymysql 连接到数据库。 我是数据库操作的新手。 是否有可用于检查数据库是否打开/活动的状态代码,例如 db.status。

从我在源代码中看到的,“连接”对象上有is_connected()方法

连接时返回 True; 否则为假

import mysql.connector

cnx = mysql.connector.connect(user='scott', password='tiger',
                              host='127.0.0.1',
                              database='employees')
print(cnx.is_connected())

我做了一个快速测试 - 连接到数据库,检查is_connected() - 它返回True ,然后停止 MySQL 并再次检查is_connected() - 返回False

旧帖子,但在这里评论以防其他人偶然发现。

来自 pymysql 文档:

ping(reconnect=True)
Check if the server is alive.

Parameters: reconnect – If the connection is closed, reconnect.
Raises: Error – If the connection is closed and reconnect=False.

代码示例

connection = pymysql.connect(host='localhost', user='root', password='password')
connection.close()

>> connection is now closed

connection.ping(reconnect=False)

>> returns an error, connection is closed

connection.ping(reconnect=True)

>> connection is reconnected

https://pymysql.readthedocs.io/en/latest/modules/connections.html

看起来您可以创建数据库对象并检查它是否已创建如果未创建您可以引发异常

尝试连接到一个明显错误的数据库,看看它抛出了什么错误,你可以在 try 和 except 块中使用它

我也是新手,所以任何有更好答案的人请随时加入

暂无
暂无

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

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