Python Forum
Closing SQL Connection within Class
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Closing SQL Connection within Class
#1
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
Reply


Messages In This Thread
Closing SQL Connection within Class - by vviiper - Jun-30-2017, 09:37 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Serial connection connection issue Joni_Engr 15 8,332 Aug-30-2021, 04:46 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020