【问题标题】:Python - 'unknown encoding: utf8mb4' when using ON DUPLICATE KEY UPDATEPython - 使用 ON DUPLICATE KEY UPDATE 时出现“未知编码:utf8mb4”
【发布时间】: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 命令的问题。当我一次运行插入一个时,我不会抛出错误。

【问题讨论】:

    标签: python-3.x mysql-python


    【解决方案1】:

    在旧版本的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/

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-10
        相关资源
        最近更新 更多