Python, mysqldb and unicode

I'm having trouble getting unicode values โ€‹โ€‹from mysql queries.

Here's how I do it now:

>>> 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'> 

As you can see, it does not return unicode.

In my table structure, Title_de is set to unicode.

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

I really don't know what I'm doing wrong, any help would be really welcome.

Thanks in advance,

Simon

+4
source share
1 answer

What you get is bytestring. You must decode it to get a unicode string. It basically boils down to the following:

 >>> byte_string = 'F\xe9vrier' >>> byte_string.decode('UTF-8') u'Fรฉvrier' 
+2
source

All Articles