Python - 'unknown encoding: utf8mb4' 使用重复密钥更新时

Python - 'unknown encoding: utf8mb4' when using ON DUPLICATE KEY UPDATE

正如标题所说,当我尝试使用 ON DUPLICATE KEY UPDATE 时收到错误 'unknown encoding: utf8mb4'。如果我改用 INSERT IGNORE,我不会收到此错误,但我会失去更新插入的能力。这是我的代码的样子:

MySQL version: 5.7.14-google-log
Python: 3.6.5
mysql-connector: 2.1.6


def mysqlLoader(vals, table, headers):
dbCon = mysql.connector.connect(
    host="-",
    user="-",
    passwd="-",
    database="-",
    charset='utf8mb4'
)

cursor = dbCon.cursor()
sql = generateSQL(table, headers, vals)
try:
    dbCon.autocommit = False
    cursor.execute('SET NAMES utf8mb4')
    cursor.execute("SET CHARACTER SET utf8mb4")
    cursor.execute("SET character_set_connection=utf8mb4")
    print('Executing SQL query...')
    cursor.executemany(sql, vals)
    print('Commiting to MySQL...')
    dbCon.commit()
    print("MySQL Updated Successfully! %s records inserted!" % cursor.rowcount)
except Exception as e:
    print("Could not commit entries: %s" % e)
    sendEmail('Data Loader Failed', 'Table: %s\r\nError: %s' % (table, e))


def generateSQL(table, headers, vals):
    valStrings = getSQLStrings(vals)
    updateVals = getUpdateString(headers)
    sql = 'INSERT INTO %s (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %s' % (table, headers, valStrings, updateVals)
    print("Query created.")
    return sql

def getUpdateString(headers):
"""Outputs an ON DUPLICATE UPDATE string using the given headers."""
temp = ''
split = headers.split(', ')
for item in split:
    temp += '%s=VALUES(%s), ' % (item, item)
temp = temp[:(len(temp)-2)]
return temp

我可以删除表情符号和其他字符并恢复为 utf8,但为了数据完整性,我更愿意保留它们。任何帮助将不胜感激。

编辑:这似乎是 executemany 命令的问题。当我 运行 一次插入一个时,我不会抛出错误。

对于任何好奇的人,我都可以通过使用 REPLACE 而不是 INSERT 来解决这个问题。不是一个完美的解决方案,但它正好符合我的需求。

在旧版本 mysql-connector 甚至最新版本 中,多次插入命令似乎存在错误mysql-connector-rf

https://dev.mysql.com/doc/relnotes/connector-python/en/news-2-1-7.html

最好的解决办法是去mysql-connector-python,也就是维护Oracle的mysql团队。 https://pypi.org/project/mysql-connector-python/