2013-02-21 54 views
0

存在unicode存儲到數據庫的問題。爲您的信息你=你..python將unicode存儲到mysql

>> 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','你') 

工程....

任何人都可以幫助我?我需要使用「數據=(‘你’,一個)」,因爲後來我將導入中國chracter文件

回答

2

試着告訴蟒蛇治療字符串爲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還你會發現這個蘇答案有幫助:Character reading from file in Python

+0

非常感謝...我怎麼樣讀取文件和商店作爲u'chinese _character' – khheng 2013-02-21 18:54:39

+0

我不確定你的意思 – 2013-02-21 18:57:02

+0

爲例,a =「你好」,那麼「a」將是' \ xc4 \ xe3 \ xba \ xc3'
如何使用'unicode()'函數嘗試使用u'\ xc4 \ xe3 \ xba \ xc3' – khheng 2013-02-21 18:59:49