【问题标题】:String encoding with Python and MySQL使用 Python 和 MySQL 进行字符串编码
【发布时间】:2017-06-22 11:34:04
【问题描述】:

我需要使用Python3 脚本将带有几个非ASCII 字符的MySQL 5.7 数据库字符串插入到MySQL 5.7 数据库中,例如è 甚至其他字母。我在utf8mb4中转换了感兴趣表的所有列。

连接

db1 = MySQLdb.connect (
host="host1",
user="user1",
passwd="secret",
db="db1"
)

cursor1 = db1.cursor()
cursor1.execute("USE db1")

我可以使用è 正确存储字符串。带有 的字符串会生成以下错误:

UnicodeEncodeError: 'latin-1' codec can't encode character '\u2026' in position 1022: ordinal not in range(256)

反之亦然,连接

db1 = MySQLdb.connect (
host="host1",
user="user1",
passwd="secret",
db="db1"
)

cursor1 = db1.cursor()
cursor1.execute("USE db1")
cur.execute("SET NAMES utf8mb4;")
cur.execute("SET CHARACTER SET utf8mb4;")
cur.execute("SET character_set_connection=utf8mb4;")

由于è而产生错误:

_mysql_exceptions.OperationalError: (1366, "Incorrect string value: '\\xE8 string...' for column 'column1' at row 1")

è 具有十六进制代码 E8

怎么了?

【问题讨论】:

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


    【解决方案1】:

    您应该在连接到数据库时尝试将编码设置为 UTF8,方法如下:

    db1 = MySQLdb.connect (
    host="host1",
    user="user1",
    passwd="secret",
    db="db1"
    use_unicode=True, 
    charset="utf8"
    )
    

    【讨论】:

      猜你喜欢
      • 2020-07-22
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      相关资源
      最近更新 更多