2016-03-22 28 views
1

sorunları utf8mb4_general_ciPython, XML ve MySQL - ASCII v utf8 kodlama olarak kodlanan bir longtext alanda depolanan XML içeriğine sahip, bir MySQL tablo var

Veritabanı Tablo I okumak için bir Python komut dosyası kullanmak istiyorum enter image description here Transcript alanından XML verilerinde, bir öğeyi değiştirin ve sonra değeri veritabanına geri yazın.

Ben ElementTree.tostring kullanarak bir Unsuru içine XML içeriğini elde etmeye çalışmak zaman aşağıdaki kodlama hatası alıyorum:

Traceback (most recent call last): 
File "ImageProcessing.py", line 33, 
    in <module> root = etree.fromstring(row[1]) 
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etre‌​e/ElementTree.py", line 1300, 
    in XML parser.feed(text) 
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etre‌​ e/ElementTree.py", line 1640, 
    in feed self._parser.Parse(data, 0) 

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2014' in position 9568: ordinal not in range(128) 

Kodu:

import datetime 
import mysql.connector 
import xml.etree.ElementTree as etree 

# Creates the config parameters, connects 
# to the database and creates a cursor 
config = { 
    'user': 'username', 
    'password': 'password', 
    'host': '127.0.0.1', 
    'database': 'dbname', 
    'raise_on_warnings': True, 
    'use_unicode': True, 
    'charset': 'utf8', 
} 
cnx = mysql.connector.connect(**config) 
cursor = cnx.cursor() 

# Structures the SQL query 
query = ("SELECT * FROM transcription") 

# Executes the query and fetches the first row 
cursor.execute(query) 
row = cursor.fetchone() 

while row is not None: 
    print(row[0]) 

    #Some of the things I have tried to resolve the encoding issue 
    #parser = etree.XMLParser(encoding="utf-8") 
    #root = etree.fromstring(row[1], parser=parser) 
    #row[1].encode('ascii', 'ignore') 

    #Line where the encoding error is being thrown 
    root = etree.fromstring(row[1]) 

    for img in root.iter('img'): 
     refno = img.text 
     img.attrib['href']='http://www.link.com/images.jsp?doc=' + refno 
     print img.tag, img.attrib, img.text 

    row = cursor.fetchone() 

cursor.close() 
cnx.close() 
+0

, orijinal sorunun çerçevesini artan riski var hata –

+0

Seamus tam yığın izleme veriniz:

Bunun yerine bu kullanmak gerekir. Yeni sorun için yeni bir soru oluşturmalı ve orijinal sorunu çözdüyseniz, sorularımı kabul etmeli ve kabul etmelisiniz. –

+0

Şimdi yeni bir soru yükledim, bu konuya geri dönmek için bunu güncelleyeceğim –

cevap

0

Elimizin her şey iyi kurulum ve veritabanı Bağlantı iyi bir şey olan Unicodes, dönüyor. ElementTree fromstring(), ne yazık ki bir Unicode değil bir bayt gerektirir. Bu ElementTree, XML üstbilgisinde tanımlanan kodlamayı kullanarak kod çözebilir.

utf_8_xml = row[1].encode("utf-8") 
root = etree.fromstring(utf_8_xml) 
+0

Daha önce denedim ama henüz 15 itibar puanı yok :( –