Encoding MySQL编码的问题

Encoding MySQL编码的问题,encoding,utf-8,character-encoding,Encoding,Utf 8,Character Encoding,我的头发有严重的问题。字符存储不正确。我的代码: 定义创建历史(自我): El错误es El siguiente: Traceback (most recent call last): File "/home/tfg/pycharm-2016.3.2/helpers/pycharm/django_manage.py", line 41, in <module> run_module(manage_file, None, '__main__', True) File "/usr/

我的头发有严重的问题。字符存储不正确。我的代码:

定义创建历史(自我):

El错误es El siguiente:

Traceback (most recent call last):
File "/home/tfg/pycharm-2016.3.2/helpers/pycharm/django_manage.py",    line 41, in <module>
run_module(manage_file, None, '__main__', True)
File "/usr/lib/python2.7/runpy.py", line 188, in run_module
fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 82, in _run_module_code
mod_name, mod_fname, mod_loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/tfg/TrabajoFinGrado/demoTFG/manage.py", line 10, in  <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-    packages/django/core/management/__init__.py", line 443, in   execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist -packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/home/tfg/TrabajoFinGrado/demoTFG/principal/management/commands/populate_db.py", line 230, in handle
self._create_Historial()
File "/home/tfg/TrabajoFinGrado/demoTFG/principal/management/commands/populate_db.py", line 217, in _create_Historial
(round(float(row[1]))+1,row[2], self.stringToDate(row[3]), unicode(row[4],'utf-8'), row[5], self.convertValue(row[6]), str(row[7])))
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
query = query % tuple([db.literal(item) for item in args])
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 278, in literal
return self.escape(o, self.encoders)
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 208, in unicode_literal
return db.literal(u.encode(unicode_literal.charset))
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 6-7: ordinal not in range(256)
回溯(最近一次呼叫最后一次):
文件“/home/tfg/pycharm-2016.3.2/helpers/pycharm/django_manage.py”,第41行,在
运行\u模块(管理\u文件,无,'.\u主\u',真)
文件“/usr/lib/python2.7/runpy.py”,第188行,在run_模块中
fname、loader、pkg_名称)
文件“/usr/lib/python2.7/runpy.py”,第82行,在运行模块代码中
模块名称、模块名称、模块加载器、包装名称)
文件“/usr/lib/python2.7/runpy.py”,第72行,在运行代码中
run_globals中的exec代码
文件“/home/tfg/TrabajoFinGrado/demofg/manage.py”,第10行,在
从命令行(sys.argv)执行命令
文件“/usr/local/lib/python2.7/dist-packages/django/core/management/___init__.py”,第443行,从命令行执行
utility.execute()
文件“/usr/local/lib/python2.7/dist-packages/django/core/management/___init__.py”,执行中第382行
self.fetch_命令(子命令)。从_argv(self.argv)运行_
文件“/usr/local/lib/python2.7/dist-packages/django/core/management/base.py”,第196行,在运行时从
self.execute(*args,**选项._dict__;
文件“/usr/local/lib/python2.7/dist packages/django/core/management/base.py”,执行中的第232行
输出=self.handle(*args,**选项)
文件“/home/tfg/TrabajoFinGrado/demofg/principal/management/commands/populate_db.py”,第230行,在handle中
self._create_Historial()
文件“/home/tfg/TrabajoFinGrado/demofg/principal/management/commands/populate_db.py”,第217行,在“创建历史记录”中
(round(float(第[1]行))+1,第[2]行,self.stringToDate(第[3]行),unicode(第[4]行,'utf-8'),第[5]行,self.convertValue(第[6]行),str(第[7]行)))
文件“/usr/local/lib/python2.7/dist packages/MySQLdb/cursors.py”,执行中第187行
query=query%元组([db.literal(item)用于args中的项])
文件“/usr/local/lib/python2.7/dist packages/MySQLdb/connections.py”,第278行,文本形式
返回self.escape(o,self.encoders)
文件“/usr/local/lib/python2.7/dist packages/MySQLdb/connections.py”,第208行,unicode_文本
返回db.literal(u.encode(unicode_literal.charset))
UnicodeEncodeError:“latin-1”编解码器无法对位置6-7中的字符进行编码:序号不在范围内(256)
剧中的人物如下:尼科尔·奥塔门迪、加·克利希

当我在python的外壳上打印characteros时,它的wah显示正确


对不起我的英语:(

好的,我会保持简短

  • 您应该在代码的早期将编码数据/STR转换为unicode。不要内联
    .decode()/.encode()/unicode()

  • 在Python2.7中打开文件时,它是以二进制模式打开的。您应该使用
    io.open(filename,encoding='utf-8')
    ,它将文件作为文本读取,并将其从utf-8解码为Unicode

  • Python 2.7 CSV模块与Unicode不兼容。您应该安装

  • 您需要告诉MySQL驱动程序您将通过Unicodes并使用UTF-8进行连接。这可以通过向连接字符串添加以下内容来完成:

    charset='utf8',
    use_unicode=True
    
  • 将Unicode字符串传递给MySQL。使用u“”前缀可避免麻烦的隐含转换

  • 您所有的CSV数据都已经是str/Unicode str。不需要转换它

  • 总而言之,您的代码如下所示:

    from backports import csv
    import io
    datos = [self.DB_HOST, self.DB_USER, self.DB_PASS, self.DB_NAME]
    
    conn = MySQLdb.connect(*datos, charset='utf8', use_unicode=True)
    cursor = conn.cursor()
    cont = 0
    
    with io.open('principal/management/commands/Historial_fichajes_jugadores.csv', 'r', encoding='utf-8') as csvfile:
        historialReader = csv.reader(csvfile, delimiter=',')
        for row in historialReader:
            if cont == 0:
                cont += 1
            else:
                cursor.execute(u'''INSERT INTO principal_historial(jugador_id, temporada, fecha, ultimoClub, nuevoClub, valor, coste) VALUES (%s,%s,%s,%s,%s,%s,%s)''',
                      round(float(row[1]))+1,row[2], self.stringToDate(row[3]), row[4], row[5], self.convertValue(row[6]), row[7]))
    
    conn.commit()
    cursor.close()
    conn.close()
    

    您可能还想看看,其中介绍了Python 2.7 Unicode是什么。

    完成了!这里的解决方案非常感谢!!非常有用:)
    from backports import csv
    import io
    datos = [self.DB_HOST, self.DB_USER, self.DB_PASS, self.DB_NAME]
    
    conn = MySQLdb.connect(*datos, charset='utf8', use_unicode=True)
    cursor = conn.cursor()
    cont = 0
    
    with io.open('principal/management/commands/Historial_fichajes_jugadores.csv', 'r', encoding='utf-8') as csvfile:
        historialReader = csv.reader(csvfile, delimiter=',')
        for row in historialReader:
            if cont == 0:
                cont += 1
            else:
                cursor.execute(u'''INSERT INTO principal_historial(jugador_id, temporada, fecha, ultimoClub, nuevoClub, valor, coste) VALUES (%s,%s,%s,%s,%s,%s,%s)''',
                      round(float(row[1]))+1,row[2], self.stringToDate(row[3]), row[4], row[5], self.convertValue(row[6]), row[7]))
    
    conn.commit()
    cursor.close()
    conn.close()