I was told that currently, what I have below will cause the database to stay open indefinitely if an error is thrown. How do I use the try catch statement to make sure that the connection closes if an error occurs?
connection = psycopg2.connect(some_stuff_in_here)
print("Connected to DB")
cursor = connection.cursor()
if __name__ == '__main__':
does_something()
cursor.close()
connection.close()
print("Disconnected from DB")
Do I do the following? I feel it still won't work because if an error occurs while trying to close the connection, the except block will still not be able to close it.
try:
cursor.close()
connection.close()
except:
print("Database Process Error")
cursor.close()
connection.close()
try: except: finallywill be the solution