python - 使用 utf8mb4 字符集的 mysql.connector 中的 executemany 方法不起作用(python)
问题描述
几天前,我发布了一个关于使用mysql.connector
Python 中的模块在 MariaDB 数据库中插入表情符号的问题。现在经过进一步调查,我能够缩小问题范围。正确更改连接的字符集和排序规则后,我能够执行单个 sql 语句,例如插入和选择值(以下代码中的示例)。在我的用例中,我一次插入/更新了几千个值。为了效率,我使用executemany
大大减少时间的方法。
在添加对表情符号的支持之前,我使用该方法没有任何问题。但是,每当我现在使用该方法时,我都会收到一个错误,告诉我这utf8mb4
是一个未知的编码。
所以这是我无法进一步了解的地方。我不知道我是否仍然做错了什么,或者mysql.connector
python 中的模块是否有错误......如前所述,仅使用单个执行方法对我来说不是一个选项,因为它需要太长时间。我正在考虑自己将多个语句写成一个。由于这个选项不是很好(特别是对于更新多行),我希望我能找到一种方法来使用该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
解决方案
推荐阅读
- cookies - 仅在启用第三方 cookie 时使用身份验证代码进行 Azure AD 身份验证
- c++ - 为什么作为参数传递的引用可以通过函数修改变量?
- c++ - 用字符串数组命名结构的成员
- ansible - Ansible 试用循环 - apache2、sqlite3、git install
- exception - 运行我的 ASP.NET Web 应用程序时出现异常错误,
- python - Python Django - 自定义添加用户保存方法
- node.js - node.js 的 node-postgres 模块中的池化如何工作
- ios - 无效的文档参考。文档引用必须有偶数个段,但用户有 1'
- google-apps-script - 更改时的 Google 表格时间戳
- javascript - 如何拆分数组并在列javascript中返回它