I´m new to programming, but I know how to Google, so I dare to ask you for help on this one after a lot of trial and error.
I have a MySQL database (db name: text, table name: text) with utf-8 encoded text (Swedish) that I want to fetch into IPython Notebook using mysql-python (MySQLdb) for further processing.
I’ve read the python documentation about Unicode and UTF-8 (http://docs.python.org/2/howto/unicode.html), but I haven´t been able to find concrete code examples even though this must be a very trivial problem.
I just want the text in Swedish to show up in IPython Notebook with special characters åäö etc. As you can see I´ve put in more or less every code snippet I´ve found on the web regarding Unicode and UTF-8, but I can´t understand where I do the mistake(s)?
Can someone please help me out?
# -*- coding: utf-8 -*-
import MySQLdb
db = MySQLdb.connect('localhost', 'user', 'password', 'text', charset='utf8', use_unicode=False)
db.set_character_set('utf8')
cursor = db.cursor()
cursor.execute('SET NAMES utf8')
cursor.execute('SET CHARACTER SET utf8')
cursor.execute('SELECT title, body FROM text LIMIT 5')
result=cursor.fetchall()
print result
Update: This is what I get back from the Print statement:
((‘F\xc3\xb6rsta rubriken’, ‘H\xc3\xa4r \xc3\xa4r lite text p\xc3\xa5 svenska’), (‘Andra rubriken’, ‘Ytterligare lite text p\xc3\xa5 ett annat spr\xc3\xa5k’))
You are printing the result of the cursor call, which is a tuple; and you are seing the Python representation of it.
If you loop through it, you’ll see your expected results:
If your output doesn’t match the above, this means your terminal doesn’t support UTF-8.