Help me please... I can't solve that problem. That message is happen after call DLL function. Of course DLL's function and return value is all right.
Error Message: UnboundLocalError: local variable 'cur' referenced before assignment
Source Code.
daDll = windll.LoadLibrary('C:\DLL\DA_PcPos.dll')
...
rtnValue = daDll.da_PcPos(3, req_char, rep_text)
if rtnValue == -1:
self.QueryData()
def QueryData(self):
global gsHOST_DB, gsPORT_DB, gsUSER_DB, gsPSWD_DB, gsSCHEMA_DB
try:
connDB = pymysql.connect(host=gsHOST_DB, port=int(gsPORT_DB), user=gsUSER_DB, passwd=gsPSWD_DB, db=gsSCHEMA_DB, charset='utf8', use_unicode=True) <- Assignment Error
cur = connDB.cursor()
cur.execute(""" SELECT DEPOSIT_DIV_NM
, DEPOSIT_DIV_CD
FROM ADM_DEPOSIT_DIV
ORDER BY ORDER_SEQ """,)
rows = cur.fetchall()
self.cbxPayMethod.Clear()
for row in rows:
self.cbxPayMethod.Append(row[0])
except:
exception = sys.exc_info()[1]
wx.MessageBox(exception.args[1], 'error', wx.OK | wx.ICON_INFORMATION)
finally:
cur.close()
connDB.close()
You just need to look at what will happen if (for example) the pymysql.connect
call throws an exception.
In that case, cur
will never be set to anything and yet you will attempt to close()
it in the finally
block.
As to how to fix it, there's a couple of ways. The first is to make your exception handling a little more fine-grained so that each potentially-excepting statement has its own catch
. That way, you know what has failed to date and what to clean up.
However, that may not be desirable since it may increase the size of your code considerably.
Another method that does not have that drawback relies on setting the variables to a sentinel value before the try
block. That way, you know they will exist and you can check their value.
In other words, something like:
connDb = None
cur = None
try:
connDb = ...
cur = ...
:
catch:
:
finally:
if cur is not None: cur.close()
if connDb is not None: connDb.close()
If the problem is more to do with the fact that an exception only occurs with a call to the DLL beforehand, you'll need to do some more investigation as there's not really enough information in the question.
For a start, I'd examine all the variables that you use for the pymysql.connect
call since they may be affected by the DLL (global variables are quite often the cause of these sorts of problems). The actual text of the exception would also be valuable.