gpt4 book ai didi

SQLAlchemy 为 BINARY 列报告 "Invalid utf8mb4 character string"

转载 作者:行者123 更新时间:2023-12-01 23:13:15 27 4
gpt4 key购买 nike

假设这个 MySQL 表架构:

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uuid` binary(16) NOT NULL,
`email` varchar(255) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`photo` binary(16) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uuid` (`uuid`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4;

当我这样使用来自 SQLAlchemy 连接类的 execute() API 时:

with self.engine.begin() as connection:
user_uuid = uuid.UUID("...")
result = connection.execute("SELECT email, name, photo FROM user WHERE uuid=%s", user_uuid.bytes)

如果 UUID 是 F393A167-A919-4B50-BBB7-4AD356E89E6B,则 SQLAlchemy 会打印此警告:

/site-packages/sqlalchemy/engine/default.py:450: Warning: Invalid utf8mb4 character string: 'F393A1'

uuid 列是一个 BINARY 列,那么为什么 SQLAlchemy 将此参数视为文本参数而不是二进制参数?如何防止这种情况发生?

最佳答案

解释和解决其实就在这个bug report in MySQL :

replace:

cursor.execute(""" INSERT INTO user (uuid) VALUES (%s) """, my_uuid)

with

cursor.execute(""" INSERT INTO user (uuid) VALUES (_binary %s) """, my_uuid)

Mind the underscore. It's "_binary", not "binary". This "_binary" tells MySQL that the following string is to be interpreted as binary, not to be interpreted/validated as utf8.

关于SQLAlchemy 为 BINARY 列报告 "Invalid utf8mb4 character string",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37899889/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com