【问题标题】:Mysql with python: problems with utf8 encodingMysql with python:utf8编码的问题
【发布时间】:2021-10-29 08:16:30
【问题描述】:

在基中插入记录时会出现编码错误。

连接是这样的:

conexion = mysql.connector.connect(host='200.**.**.**',
                                       database='database',
                                       user='user',
                                       password='password',
                                        port=3306,
                                    charset='utf8'
                                  )

通过这种预处理:

nombre = nombre.replace("\'", "\\'")

查询:

query = "INSERT INTO table(field) VALUES('"+nombre[0:250]+"')"
cursor = conexion.cursor()
cursor.execute(query)
conexion.commit()
cursor.close()

错误信息是:

DatabaseError: 1366 (HY000): Incorrect string value: '\xF0\x9D\x95\x8B\xF0\x9D...' for column 'nombre' at row 1

在数据库中该字段定义为:

`nombre` varchar(250) COLLATE utf8_spanish_ci DEFAULT NULL,

针对相应的错误消息尝试以下替代方案:

一)

nombre = nombre.replace("\'", "\\'")
nombre = str(nombre, 'utf-8')
query = "INSERT INTO table(field) VALUES('"+nombre[0:250]+"')"

TypeError: decoding str is not supported

b)

nombre = nombre.replace("\'", "\\'")
nombre = nombre.decode('utf-8')
query = "INSERT INTO table(field) VALUES('"+nombre[0:250]+"')"

AttributeError: 'str' object has no attribute 'decode'

c)

nombre = nombre.replace("\'", "\\'")
nombre.decode('unicode_escape').encode('iso8859-1').decode('utf8')
query = "INSERT INTO table(field) VALUES('"+nombre[0:250]+"')"

AttributeError: 'str' object has no attribute 'decode'

还有其他解决方案吗? 非常感谢您的帮助。

【问题讨论】:

  • nombre是如何在数据库中定义的...?
  • 另外,这不是您执行 SQL 查询的方式!使用参数化查询!像cursor.execute('INSERT ... VALUES (%s)', (nombre,)) 这样的东西。然后也跳过replace
  • @deceze 编辑帖子以提供更多信息。谢谢

标签: python-3.x utf-8 character-encoding mysql-python


【解决方案1】:

这样解决:

cursor = conexion.cursor()
cursor.execute('SET NAMES utf8;')
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_connection=utf8;')
cursor.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 2013-04-25
    • 1970-01-01
    相关资源
    最近更新 更多