2011-09-05 87 views
4

我無法從mysql查詢中獲取unicode值。Python,mysqldb和unicode

這裏是我如何做到這一點現在:

>>> from MySQLdb import connect 
>>> from MySQLdb.cursors import DictCursor 
>>> con = connect(
    passwd = "****", 
    db = 'my_db', 
    user = "db_user", 
    host = "localhost", 
    cursorclass = DictCursor, 
    use_unicode=True, 
    charset="utf8" 
) 
>>> cursor = con.cursor() 
>>> cursor.execute (u'Select * from basic_applet') 
>>> res = cursor.fetchall() 
>>> print(res) 
({'Title_de': 'test title', .... }) 
>>> type(res[0]['Title_de']) 
<type 'str'> 

正如你所看到的,它沒有返回的Unicode。

在我的表結構中,Title_de被設置爲unicode。

IDbasic_applet int(10)... 
Title_de varchar(75)  utf8_bin 

我真的不知道我在做什麼錯,任何幫助都會非常受歡迎。

由於提前,

西蒙

回答

2

你得到的是一個字節串。你必須解碼才能得到一個unicode字符串。它基本上歸結爲:

>>> byte_string = 'F\xe9vrier' 
>>> byte_string.decode('UTF-8') 
u'Février' 
+0

據我所知,事實是,我認爲有可能要求unicode字符串,而不是字節字符串。你知道use_unicode = True的效果嗎? –

+0

它對我來說有理想的效果。我的列定義包含'CHARACTER SET UTF8'而不是'utf8_bin'。 Afaik這是唯一的區別。 – pvoosten

+1

@SimonRolin問他的問題已經有一段時間了,但僅僅是爲了記錄MySQLdb.connect(use_unicode = True,charset ='utf8',...)'使得MySQL返回unicode。 – mcrisc