Prøv:
con = mdb.connect('loclhost', 'root', '', 'mydb',
use_unicode=True, charset='utf8')
Her er en demonstration, der viser, at det virker:
Hvis du ikke bruger use_unicode=True
med følgende opsætning får du en UnicodeEncodeError:
import MySQLdb
import config
def setup_charset(cursor, typ='latin1'):
sql = 'DROP TABLE IF EXISTS foo'
cursor.execute(sql)
sql = '''\
CREATE TABLE `foo` (
`fooid` int(11) NOT NULL AUTO_INCREMENT,
`bar` varchar(30),
`baz` varchar(30),
PRIMARY KEY (`fooid`)) DEFAULT CHARSET={t}
'''.format(t=typ)
cursor.execute(sql)
sql = 'INSERT INTO foo (bar,baz) VALUES (%s,%s)'
connection = MySQLdb.connect(
host=config.HOST, user=config.USER,
passwd=config.PASS, db='test')
cursor = connection.cursor()
setup_charset(cursor, typ='utf8')
sql = u'INSERT INTO foo (bar,baz) VALUES (%s,%s)'
try:
cursor.execute(sql, [u'José Beiträge', u'∞'])
except UnicodeEncodeError as err:
# You get this error if you don't use
# (use_unicode=True, charset='utf8') see below.
print(err)
rejser undtagelsen:
'latin-1' codec can't encode character u'\u221e' in position 0: ordinal not in range(256)
Mens, hvis du bruger use_unicode=True
, du kan indsætte unicode uden fejl:
connection = MySQLdb.connect(
host=config.HOST, user=config.USER,
passwd=config.PASS, db='test',
use_unicode=True,
charset='utf8')
cursor = connection.cursor()
cursor.execute(sql, ['José Beiträge', '∞'])
cursor.execute('SELECT * from foo')
for row in cursor:
print(u'{} {}'.format(*row[1:]))
udskrifter
José Beiträge ∞