Mysql
 sql >> Database >  >> RDS >> Mysql

Problema di codifica Unicode Python

Prova:

con = mdb.connect('loclhost', 'root', '', 'mydb', 
                  use_unicode=True, charset='utf8')

Ecco una dimostrazione che mostra che funziona:

Se non usi use_unicode=True con la seguente configurazione, ottieni un 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)

solleva l'eccezione:

'latin-1' codec can't encode character u'\u221e' in position 0: ordinal not in range(256)

Mentre, se usi use_unicode=True , puoi inserire unicode senza errori:

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:]))

stampe

José Beiträge ∞