我正在编写一个脚本,该脚本将从我们的星号系统回填呼叫详细信息记录到我们的 MySQL 日志数据库中。在下面的代码中,我试图忽略重复的键并继续到下一行,但是当此代码执行时,我所看到的只是第一行重复警告,然后脚本退出(下面的示例 2。)导致它失败的明显错误?
原谅我可怜的 python 礼仪,我对这门语言很陌生。我的假设是,即使 pass 可能会出现异常,foreach 循环也无法生存。
编辑/注意:在我解决了退出 for 循环的问题之后,这也值得一提:因为我有一个finally:
关闭 sql 连接的块,该finally:
块是在except: pass
关闭连接之后执行的。所以在上面的例子中,finally:
仍然导致程序异常结束。
#!/usr/bin/python -d
import csv
import sys
import MySQLdb as mdb
log="Master.csv"
try:
con = mdb.connect('1.2.3.4','abcd','efgh','ijkl')
cur = con.cursor()
#Inefficient way of getting row count.
rcount = csv.reader(open(log, 'rb'))
print "Number of rows in csv: %d" % (len(list(rcount)))
#OK, real csv processing now.
reader = csv.reader(open(log, 'rb'))
iter = 0
for row in reader:
print "Row: %d" % (++iter)
clid = row[0]
src = row[1]
dst = row[2]
dcontext = row[3]
channel = row[4]
dstchannel = row[5]
lastapp = row[6]
lastdata = row[7]
start = row[8]
end = row[10]
duration = row[11]
billsec = row[12]
disposition = row[13]
amaflags = row[14]
accountcode = row[15]
uniqueid = row[16]
insertstr= "INSERT INTO cdr_extended (duration,billsec,amaflags,start,end,clid,src,dst,dcontext,channel,dstchannel,lastapp,lastdata,disposition,accountcode,uniqueid) VALUES (%s,%s,0,'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s');" % (duration,billsec,start,end,clid,src,dst,dcontext,channel,dstchannel,lastapp,lastdata,disposition,accountcode,uniqueid)
cur.execute(insertstr)
con.commit()
except mdb.Error, e:
if e.args[0] == 1062:
print "Dupe key on uniqueid: %s" % (uniqueid)
pass
else:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
finally:
if con:
con.close()
输出:
Number of rows in csv: 2696
Row: 0
Dupe key on uniqueid: 1342632723.8