mysql.connector 中的 executemany 方法与 utf8mb4 字符集不起作用python

问题描述

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

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

所以这是我无法进一步了解的地方。我不知道我是否仍然做错了什么,或者python中的mysql.connector模块是否有错误...... 如前所述,仅使用单个执行方法对我来说不是一种选择,因为它会花费太长时间。我正在考虑自己将多个语句写成一个。由于这个选项不是很好(尤其是更新多行),我希望我能找到一种方法来使用 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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...