Mysqldb Error Local Variable Referenced Before Assignment (different Than Usual)
Solution 1:
The issue is that item
is only assigned when you enter the for
loop
for item in data['items']:
...
If data['items']
is empty, you never do so, and item
remains unassigned.
Solution 2:
Since this script iterates through the loop and some of the returned variables are NULL python then (rightfully so) throws the UnboundLocalError as the variable isn't there/hasn't been declared.
I attempted to handle this problem by using:
except KeyError:
However, the errors we are dealing with here aren't only KeyErrors but also UnboundLocalErrors, so handling only one of the errors wasn't effective.
I modified the script in the following way (mind you this works in Python 2.7 I am not sure if the same syntax is possible in Python 3):
try:
description = item['particulars']['description']
except (UnboundLocalError, KeyError):
#declaring the description as None if not there so MySQL/Python don't throw an error
description = None
and then when adding data to MySQL database I am also using the error handler and passing if there is one:
try:
cursor.execute("""INSERT INTO companies_and_charges_tmp (etags, company_id, created, delivered, satisfied, status, description, persons_entitled) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""", (item.get('etag'), ch_no, item.get('created_on'), item.get('delivered_on'), item.get('satisfied_on'), item.get('status'), description, persons_entitled))
db.commit()
except UnboundLocalError:
pass
Post a Comment for "Mysqldb Error Local Variable Referenced Before Assignment (different Than Usual)"