【发布时间】:2019-04-03 17:42:30
【问题描述】:
正如标题所说,当我尝试使用 ON DUPLICATE KEY UPDATE 时收到错误“未知编码:utf8mb4”。如果我使用 INSERT IGNORE 代替,我不会收到此错误,但是我失去了 upsert 的能力。这是我的代码的样子:
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 命令的问题。当我一次运行插入一个时,我不会抛出错误。
【问题讨论】: