Python - 使用重复键更新时的'unknown encoding: utf8mb4'



就像标题说的那样,当我尝试使用ON DUPLICATE KEY UPDATE时,我收到了错误"未知编码: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: %srnError: %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,但为了数据完整性,我更愿意保留它们。任何帮助都将不胜感激。

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

当涉及到旧版本的mysql连接器中的多重插入命令时,甚至在最新版本的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/

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

最新更新