タイトルのように、ON DUPLICATE KEY UPDATEを使用しようとすると、「不明なエンコーディング:utf8mb4」というエラーが表示されます。代わりにINSERTIGNOREを使用してもこのエラーは発生しませんが、アップサートする機能が失われます。これは私のコードがどのように見えるかです:
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コマンドの問題のようです。一度に1つずつ挿入を実行しても、エラーはスローされません。
興味のある人のために、INSERTの代わりにREPLACEを使用するだけでこれを回避することができました。完璧な解決策ではありませんが、私のニーズにぴったりです。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加