Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pymysql

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.

like image 962
Yan Song Avatar asked Dec 26 '17 02:12

Yan Song


1 Answers

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.

like image 88
alecxe Avatar answered Oct 10 '22 01:10

alecxe