我有一个python脚本,它从互联网(从URLS列表)下载某些数据,并将其存储在MySQL数据库中。我的代码就是这样的:
try:
con = mdb.connect(host = 'localhost', user = 'root', passwd = 'gatech', db ='SpecialProb', charset = 'utf8');
cur = con.cursor()
print " Database Connection Parameters set"
except mdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
try:
for item in listURLs[index:]:
try:
r2 = requests.get(item)
except:
print "Could not fetch data"
print "Exception: ", sys.exc_info()[0]
continue
## Some code to fetch Name, ID from the internet, which I have tested and which works correctly. ##
try:
cur.execute("INSERT into TABLENAME (NAME, ID"
") VALUES (%s, %s)",
(totalName, ID))
print("Value inserted in database.\n")
countInsert += 1;
con.commit()
except mdb.IntegrityError:
print "Most likely cause: Database already contains this entry."
print "Message from system: "
print "Error %d: %s\n" % (e.args[0],e.args[1])
continue
except:
print "'For loop exception: ", sys.exc_info()[0]
sys.exit(0)我获取的数据可能是重复的,我不希望将重复的数据插入到数据库中,代码应该在下一次迭代中进行,蚀刻下一个数据,而不是存储数据。所以我有一条except mdb.IntegrityError:线,它负责复制。
但是,在捕获了重复条目的异常后,代码将不再进行下一次迭代,而是转到我为for循环设置的for。我得到的是:
Most likely cause: Database already contains this entry.
Message from system:
'For loop exception: <type 'exceptions.NameError'>这一切为什么要发生?我怎么才能防止这种情况发生呢?
非常感谢!
发布于 2014-02-13 03:41:10
您的e不会被定义,从而导致您的not块中的异常。使用mdb.IntegrityError,e就像使用except mdb.Error, e一样
https://stackoverflow.com/questions/21744621
复制相似问题