You can make a context manager with your class:
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
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-connectionHere 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!
All humans together. We don't need politicians!