【发布时间】:2018-06-06 23:39:00
【问题描述】:
我正在使用 pymysql 连接到数据库。我是数据库操作的新手。是否有一个状态码可用于检查数据库是否处于打开/活动状态,例如 db.status。
【问题讨论】:
我正在使用 pymysql 连接到数据库。我是数据库操作的新手。是否有一个状态码可用于检查数据库是否处于打开/活动状态,例如 db.status。
【问题讨论】:
从我在源代码中看到的,“连接”对象上有is_connected() method:
连接时返回 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。
【讨论】:
is_connected() 方法的正确链接。谢谢。
旧帖子,但在这里发表评论以防其他人偶然发现。
来自 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 块中使用它
我也是新手,如果有更好的答案,请随时加入
【讨论】: