The following code cx_Oracleworks fine when the database is completed:
import cx_Oracle
try:
conn = cx_Oracle.connect("scott/tiger@oracle")
try:
curs = conn.cursor()
curs.execute("SELECT dummy FROM sys.dual")
print curs.fetchone()[0]
finally:
curs.close()
finally:
conn.close()
But if the database does not work, when I run this script, it is created NameError:
Traceback (most recent call last):
File "C:\Users\ArtMetzer\Documents\Code\Python\db_conn_test.py", line 14, in <module>
conn.close()
NameError: name 'conn' is not defined
This makes sense to me: cx_OracleI could not create an instance of the connection, so the variable was connnever set and therefore has no method close().
In Python, what is the best way to ensure that the database connection is closed while still gracefully processing the database state down?
Doing something like the following seems like a huge shred to me:
finally:
try:
conn.close()
except NameError:
pass
source
share