存储在unicode(在数据库中)的数据必须被检索并转换为不同的形式。使用python从sqlite db读取unicode
下面的代码片断
def convert(content):
content = content.replace("ஜௌ", "n\[s");
return content;
mydatabase = "database.db"
connection = sqlite3.connect(mydatabase)
cursor = connection.cursor()
query = ''' select unicode_data from table1'''
cursor.execute(query)
for row in cursor.fetchone():
print convert(row)
产生在转换方法下面的错误消息。
exceptions.UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128)
如果数据库内容为“ஜௌஜௌஜௌ”,输出应该是“N \ [SN \ [SN \ [秒”
的文档建议使用忽略或替换,以避免错误,当创建unicode字符串。
时,按如下迭代变化:
for row in cursor.fetchone():
print convert(unicode(row, errors='replace'))
返回
exceptions.TypeError: decoding Unicode is not supported
其告知该行已经是一个unicode。
任何光线都可以使它工作,我们非常感谢。提前致谢。
什么版本的Python你正在用吗? – fuzzyanalysis 2012-02-05 10:18:37
其python 2.6.3。 – Gopal 2012-02-05 10:52:19
尝试在您的python脚本中使用'u“例子”'输入unicode字符串。这很刺激,但Python 2有两种类型的字符串,“unicode”和“str”。不确定技术方面,例如,这些可能是8位(例如使用UTF-8编码)和16位字符串。另外,你可能想要'\\ ['? – 2012-02-05 11:41:02