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

Yan Song picture Yan Song · Dec 26, 2017 · Viewed 8.5k times · Source

I am using pymysql to connect to a database. I am new to database operations. Is there a status code that I can use to check if the database is open/alive, something like db.status.

Answer

alecxe picture alecxe · Dec 26, 2017

From what I see in the source code, there is the is_connected() method on a "connection" object:

Returns True when connected; False otherwise

import mysql.connector

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

I've done a quick test - connected to the database, checked the is_connected() - it returned True, then stopped MySQL and checked the is_connected() again - returned False.