How to check database connection in python?

I am accessing a MySQL database from python through the MySQLdb library. I am trying to check the database connection as shown below.

db = MySQLdb.connect(self.server, self.user, self.passwd, self.schema) cursor = db.cursor() try: cursor.execute("SELECT VERSION()") results = cursor.fetchone() ver = results[0] if (ver is None): return False else: return True except: print "ERROR IN CONNECTION" return False 

Is it necessary to check the connection correctly when writing test modules? If there is a better way, please enlighten!

+6
source share
2 answers

I could be wrong (or misinterpreted your question :)), but I believe that the connection-related exception is thrown at MySQLdb.connect() . With MySQLdb, the exception for catch is MySQLdb.Error . Therefore, I would suggest moving the db settings inside the try block and MySQLdb.Error correct exception ( MySQLdb.Error ). Also, as @JohnMee mentions, fetchone() returns None if there are no results, so this should work:

 try: db = MySQLdb.connect(self.server, self.user, self.passwd, self.schema) cursor = db.cursor() cursor.execute("SELECT VERSION()") results = cursor.fetchone() # Check if anything at all is returned if results: return True else: return False except MySQLdb.Error: print "ERROR IN CONNECTION" return False 

If you don’t care about the connection and just want to check the execution of the request, I think you can leave the connection settings outside of try , but include MySQLdb.Error in your exception, perhaps as follows:

 db = MySQLdb.connect(self.server, self.user, self.passwd, self.schema) cursor = db.cursor() try: cursor.execute("SELECT VERSION()") results = cursor.fetchone() # Check if anything at all is returned if results: return True else: return False except MySQLdb.Error, e: print "ERROR %d IN CONNECTION: %s" % (e.args[0], e.args[1]) return False 

This, at least, will give you a more detailed reason why this failed.

+8
source

Yes. It looks good to me.

My personal preferences:

  • really throws an exception if the connection
  • you only need fetchone, the test for None is superfluous (if you are not interested in the minimum version of the database)
+1
source

Source: https://habr.com/ru/post/921743/