🇩🇪 Deutsch

13 Jan 2021

Python und Mysql: UnicodeEncodeError

Bei der Verwendung von MySQL via Python kann man auf folgenden Fehler stossen:

“UnicodeEncodeError:’latin-1’ codec can’t encode character …”

Dies wird dadurch verursacht, weil MySQLdb unter Umsta”nden alles zu latin-1 kodiert. Abhilfe schafft man durdh

db.set_character_set('utf8')
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')

“db” is the result of MySQLdb.connect(), and “dbc” is the result of db.cursor().