Python将Unicode存储到MySQL
我在把unicode字符存储到数据库时遇到了问题。顺便说一下,"你"这个字在这里是指"you"。
>> a='你'
>>a <\br>
'\xc4\xe3'
问题是
# -*- coding: utf-8 -*-
import MySQLdb
db = MySQLdb.Connect(host="127.0.0.1", port=3306, user="root", passwd="root",db="mydata", charset="utf8", use_unicode=True)
cursor = db.cursor()
insert = "insert into testing (english,chinese,frequency) values(%s,%s,1) on duplicate KEY UPDATE frequency=frequency+1;"
a='你'
data=('you',a)
try:
cursor.execute(insert,data)
except:
print "error"
db.commit()
这段代码让我出现了错误,但当我改成这样
data=('you','你')
就能正常工作了……
有没有人能帮帮我?我需要用"data=('you',a)",因为之后我还要导入中文字符文件。
1 个回答
2
试着告诉Python把字符串当作Unicode来处理,比如这样写:a= u'你'
如果你不是在使用交互式命令行,可以通过unicode
这个函数来实现。加载数据的一种方法示例如下:
fname = 'somefile.txt'
with open(fname,'r') as f
unicode_data = unicode(f.read())
如果这样还是不行,你可以在Python的文档里找到更多详细信息:http://docs.python.org/2/howto/unicode.html,另外你也可以参考这个StackOverflow的回答:在Python中从文件读取字符