Python插入XML中的UTF字符到MySQL时出现问题

3

我正在遍历多个大型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)

1
首先,不要使用裸的 except,这样你就可以知道出了什么问题。 - Martijn Pieters
谢谢您的快速回复。我对Python还是完全陌生的,所以还在摸索中。我将上一个except更改为:except Exception as e: print "Something bad happened while reading and inserting." print e现在我得到了“读取和插入时发生了一些错误。需要多于1个值来解包”的提示。 - evildrx
1个回答

2

很少有人有耐心去处理所有的代码。

首先要做的是摆脱每个try...except。Python仍然会快乐地引发异常,没有它也可以。

只有在想要在除了错误查找之外对异常进行一些特殊处理时才需要使用try...except。在这个阶段,打印语句是更好的朋友。此外,如果您省略try...excepts(至少您正在使用它们的方式),Python也将打印回溯,这也是您应该随代码发布的内容。

请在整理代码后发布此回溯。

编辑:感谢回溯信息。现在我们可以看到您使用的编码(utf-8)与MySQLdb Python库使用的默认编码(latin-1)之间存在不匹配。您需要将charset='utf8'作为参数传递给connect()。('utf8'中没有破折号,因为这是MySQL存储其字符集列表的方式。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接