Function Code:
try:
dbi = MySQLdb.connect(host='localhost', \
user='user', \
passwd='pass', \
db='dbname', \
port=3309)
print "Connected to DB ..."
except MySQLdb.Error, e:
apiErr = 2
apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
return
try:
try:
sql = dbi.cursor()
sql.execute("""
SELECT *
FROM table
WHERE idClient = %s
""", (key, ))
access = sql.fetchall()
except MySQLdb.Error, e:
apiErr = 2
apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
return
finally:
sql.close()
dbi.close()
I understand that in an attempt ... except ... finally, the finally block will always be executed. In the above code, I do not want to finally execute in the second try block if there is an exception in the first try block. What am I doing wrong?
(Note: using python 2.4)
Clarification: I do not know whether MySQLdb will automatically close connections when an error occurs. The problem I encountered with the above code is when an error occurs while establishing a connection (the first try code block), calling dbi.close () in the finally block raises "AttributeError: the NoneType object does not have a close attribute with link to dbi ...
Solution : This worked as desired -
dbi = None
sql = None
In the finally block
if sql is not None:
sql.close()
if dbi is not None:
dbi.close()
, . - . ( :).
Sam