Reputation: 165
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()
Upvotes: 1
Views: 2209
Reputation: 44285
The connection will close when the python process exits. Unless the python process is a long-running daemon, there is nothing to worry about.
Trying to catch this seems pointless. If the connection refuses to close in the normal course, what are you going to do about it in the exceptional case? Presumably it still won't close there either, as nothing has changed. About the only way catching this makes sense is if the python is a long-running process, and the exception condition results in an abort of that process which would otherwise not occur.
Upvotes: 0
Reputation: 6723
It's probably easiest to use the connection and cursor as context managers (the with statement):
From the docs:
with psycopg2.connect(your_stuff_in_here) as conn:
with conn.cursor() as curs
curs.execute('SELECT * FROM test')
This will automatically clean up after any errors. If you need more fine-grained control over the errors you can use try/catch/finally.
Upvotes: 1