utf8mb4字符集不工作的mysql.connector中的executemany方法(python)

2024-05-06 10:41:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

所以这就是我不能再继续下去的地方。我不知道我是否仍在做错事,或者python中的mysql.connector模块中是否有错误。。。 正如前面提到的,我不选择只使用单执行方法,因为它会花费太长的时间。我想自己把多个陈述写成一个。由于这个选项不是很好(特别是对于更新多行),我希望我能找到一种不用牺牲emoji支持就可以使用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

Tags: 方法pytestconnectormysqlthiscursorfile