Python Forum

Full Version: Closing SQL Connection within Class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've created a separate Python file with a class stored in it. I'm using the mysql.connector module to perform my mysql connection and queries. This is how the class is setup at the moment:

class sqlConnection():
  
  def __init__(self):
    #SQL Connection variables
    sqlServer = ''
    sqlUsername = ''
    sqlPassword = ''
    sqlDatabase = ''
    
    #Establish connection to SQL server
    try:
      con = mysql.connector.connect(host=sqlServer,user=sqlUsername,password=sqlPassword, database=sqlDatabase)
      print "Connection to SQL server success: %s, %s" % (sqlServer, sqlDatabase)
    except:
      print "Connection to SQL server failed: %s, %s" % (sqlServer, sqlDatabase)
    
  def exit_handler(self):
    #Close connection to SQL server is server closed
    self.con.close()
      
    print "Connection closed to SQL server: %s" % (sqlServer)
The class is imported in my main Python file like so:

import sqlConnection

sqlHandler = sqlConnection.sqlConnection()
My worry is that when the application closes, the SQL connection will remain open. I've tried using the exit_handler() function within the class to close the connection, but that never seems to be called when the application closes.

I did a bit of Googling but haven't been able to find an answer to this. Can any of you guys help?

Thanks,

Isaac
You can make a context manager with your class:

class sqlConnection():
   def __init__(self):
       #SQL Connection variables
       sqlServer = ''
       sqlUsername = ''
       sqlPassword = ''
       sqlDatabase = ''
    
       #Establish connection to SQL server
       try:
           con = mysql.connector.connect(host=sqlServer,user=sqlUsername,password=sqlPassword, database=sqlDatabase)
           print "Connection to SQL server success: %s, %s" % (sqlServer, sqlDatabase)
       except:
           print "Connection to SQL server failed: %s, %s" % (sqlServer, sqlDatabase)


   def __enter__(self):
       return self


   def __exit__(self, *args):
       #Close connection to SQL server is server closed
       self.con.close()
       print "Connection closed to SQL server: %s" % (sqlServer)


with sqlConnection() as conn:
   # do stuff with conn
# leaving the block closes the db-connection
Here you'll get more information: https://jeffknupp.com/blog/2016/03/07/py...-managers/

PS: Your indentation was wrong. 4 spaces per indentation. No tabulator. If you mix tabulator and spaces, you'll get an Error with Python 3.x