首页 > 解决方案 > 使用 utf8mb4 字符集的 mysql.connector 中的 executemany 方法不起作用(python)

问题描述

几天前,我发布了一个关于使用mysql.connectorPython 中的模块在 MariaDB 数据库中插入表情符号的问题。现在经过进一步调查,我能够缩小问题范围。正确更改连接的字符集和排序规则后,我能够执行单个 sql 语句,例如插入和选择值(以下代码中的示例)。在我的用例中,我一次插入/更新了几千个值。为了效率,我使用executemany大大减少时间的方法。

在添加对表情符号的支持之前,我使用该方法没有任何问题。但是,每当我现在使用该方法时,我都会收到一个错误,告诉我这utf8mb4是一个未知的编码。

所以这是我无法进一步了解的地方。我不知道我是否仍然做错了什么,或者mysql.connectorpython 中的模块是否有错误......如前所述,仅使用单个执行方法对我来说不是一个选项,因为它需要太长时间。我正在考虑自己将多个语句写成一个。由于这个选项不是很好(特别是对于更新多行),我希望我能找到一种方法来使用该executemany方法,而不会牺牲对表情符号的支持。

代码示例:

import mysql.connector

cnx = mysql.connector.connect(
    user="username",
    password="password",
    database="db_test",
    charset='utf8mb4',
    collation='utf8mb4_general_ci'
)

cnx.set_charset_collation('utf8mb4', 'utf8mb4_general_ci')

cursor = cnx.cursor()

# This works without any problems
cursor.execute("INSERT INTO test VALUES ('')")

cnx.commit()

# This works just fine too
cursor.execute("SELECT * FROM test")

result = cursor.fetchall()

print(result)

# This does not work
cursor.executemany("INSERT INTO test VALUES (%s)", ["", ""])

cnx.commit()

追溯:

Traceback (most recent call last):
  File "c:\xampp\htdocs\py\db_test.py", line 28, in <module>
    cursor.executemany("INSERT INTO test VALUES (%s)", ["", ""])
  File "C:\Python39\lib\site-packages\mysql\connector\cursor.py", line 652, in executemany
    stmt = self._batch_insert(operation, seq_params)
  File "C:\Python39\lib\site-packages\mysql\connector\cursor.py", line 582, in _batch_insert
    fmt = matches.group(1).encode(self._connection.charset)
LookupError: unknown encoding: utf8mb4

标签: pythonmysqldatabaseutf8mb4executemany

解决方案


推荐阅读