我正在遍历多个大型xml文件,并生成MySQL插入语句以将出租物业列表添加到数据库中。问题是,许多元素包含特殊字符,如Å或ç甚至一些破折号和圆点。
我可以很好地获取元素,并且可以创建一个字符串来保存插入语句,但是一旦我尝试执行该语句,我就被转到下一个文件。
我将插入放在自己的try块中,认为这只会让我继续进行下一个列表,而不是废弃剩余的xml文档,但事实并非如此。
我已经尝试确保插入是utf-8编码,但没有任何区别。
以下是我拥有的代码要点:
try:
print "About to read file: "+fullpath
data = f.read() #read the file into a string
print "Data read from file, now closing: "+fullpath
f.close() #close the file, we don't need it any more
dom = minidom.parseString(data) #parse the xml
#get the first child node -- <property_data>
property_data = dom.firstChild
properties = property_data.getElementsByTagName('property')
for property in properties:
try:
print "getting details"
details = property.getElementsByTagName('property_details')
for detail in details:
print "attempting to get detail values"
try:
checkin = getElementValue('check_in', detail)
name = stripCDATA(getElementValue('name', detail))
checkout = getElementValue('check_out', detail)
...etc, etc...
print "building insert string"
sql = u"""insert into PROPERTY(NAME, CHECKIN, CHECKOUT, etc...)
values(%s,%s,%s,...)""".encode('utf-8')
print "starting insert with query:"
print sql % (name,checkin,checkout, etc...)
try: #HERE IS WHERE THE PROBLEM HAPPENS
cursor.execute(sql,(name, checkin, checkout, ...))
#display number of rows affected
print "Number of rows inserted: %d" % cursor.rowcount
conn.commit()
except Exception as (errno, strerror):
print "Problem inserting the property. Error({0}): {1}".format(errno, strerror)
except Exception as (errno, strerror):
print "Problem with reading/inserting details. Error({0}): {1}".format(errno, strerror)
except Exception as (errno, strerror):
print "The loop broke with the following error({0}): {1}".format(errno, strerror)
errCount += 1
print "This has happened %d times" % (errCount)
except: #HERE IS WHERE I GET DUMPED TO
print "Something bad happened while reading and inserting"
正如您所看到的,我在各个位置打印出行,以便查看何时发生故障。 我知道它正确解析文件,我知道它正确获取所有我的元素,我知道它正确构建插入语句,并且只要我用任何一个元素中没有特殊字符的属性,我知道它正确地插入数据库。但是一旦它遇到特殊字符就会崩溃,当它崩溃时,它将我弹出3个级别比应该的高。尝试大喊大叫和拉扯我的头发是无效的。 有什么想法吗? 根据@deadly的建议,我删除了所有try...except块,得到了以下traceback: Traceback(最近的调用最先): 文件“dbinsert2.py”,第118行,in cursor.execute(sql,([bunch of var names])) 文件“/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py”的第159行,在执行中 查询=查询% db.literal(args) 文件“/usr/lib/python2.7/dist-packages/MySQLdb/connections.py”的第264行,literal(返回自我逃逸,self.encoders) 文件 “/usr/lib/python2.7/dist-packages/MySQLdb/connections.py”中的第202行,unicode_literal return db.literal(u.encode(unicode_literal.charset)) UnicodeEncodeError:“latin-1”编解码器不能在第20位编码字符u'\u2013':序数不在范围内(256)
except
,这样你就可以知道出了什么问题。 - Martijn Pietersexcept
更改为:except Exception as e: print "Something bad happened while reading and inserting." print e
现在我得到了“读取和插入时发生了一些错误。需要多于1个值来解包”的提示。 - evildrx