Python Forum
Closing SQL Connection within Class
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Closing SQL Connection within Class
#2
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
Closing SQL Connection within Class - by vviiper - Jun-30-2017, 09:37 PM
RE: Closing SQL Connection within Class - by DeaD_EyE - Jul-02-2017, 08:27 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Serial connection connection issue Joni_Engr 15 8,195 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