9

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.

Yan Song
  • 2,285
  • 4
  • 18
  • 27

3 Answers3

9

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.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • I checked the source code. Is there a typo in your answer? There is only a ' connected' method, not 'is_connected'. – Yan Song Dec 26 '17 at 03:19
  • @YanSong yeah, that was just the underlying C "property" I've started the research with - updated with a proper link to the `is_connected()` method. Thanks. – alecxe Dec 26 '17 at 03:58
1

Old post, but commenting here in case someone else stumbles on this.

From the pymysql docs:

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.

Code example

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

JohnL_10
  • 549
  • 5
  • 15
-4

It looks like you can create the database object and check if it has been created if it isn't created you can raise an exception

Try connecting to an obviously wrong db and see what error it throws and you can use that in a try and except block

I'm new to this as well so anyone with a better answer please feel free to chime in

L.Rengel
  • 3
  • 3