Reputation: 147
having problem to store unicode to database. for your information 你 = you..
>> a='你'
>>a <\br>
'\xc4\xe3'
the problem is
# -*- 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()
which return me an error, but when i change to this
data=('you','你')
it works....
can anyone help me?? i need to use "data=('you',a)" because later i will import chinese chracter file
Upvotes: 0
Views: 679
Reputation: 8558
Try telling python to treat the string as unicode, like this: a= u'你'
If you're not using an interactive prompt, you can accomplish this via the unicode
function. An example of one way to load data would be:
fname = 'somefile.txt'
with open(fname,'r') as f
unicode_data = unicode(f.read())
If this doesn't work, you should be able to fine more details in the python docs: http://docs.python.org/2/howto/unicode.html and also you may find this SO answer helpful: Character reading from file in Python
Upvotes: 2