python - “charmap”编解码器无法在位置 0 : character maps to <undefined> MariaDB and SQLAlchemy 处对字符 '\u010c' 进行编码

标签 python sqlalchemy mariadb decode encode

我正在尝试使用 SQLAlchemy 将数据插入到 MariaDB 数据库中。我正在解析 XML 文件以获取需要插入的数据。我读取数据没有问题。关于此错误的许多问题,例如此 python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>指从文件中读取数据。但是,我在这一步遇到错误,

con_string = db_driver + '://' + db_user + ':' + db_password + '@' + db_host + ':' + db_port + '/' + db_name
engine = sqlalchemy.create_engine(con_string, pool_pre_ping=True)

meta_data = sqlalchemy.MetaData(engine)
table = sqlalchemy.Table('table', meta_data, autoload=True, autoload_with=engine)
table.insert().execute(data)

data 是一个字典。它包含通过解析映射到表列的 XML 文件获得的值。

可能是什么原因?

最佳答案

为了支持全范围的 Unicode 字符,我们需要将 ?charset=utf8mb4 添加到连接 URL 的末尾,如

中所述

https://docs.sqlalchemy.org/en/14/dialects/mysql.html#charset-selection

例如,

e = create_engine(
    "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")

关于python - “charmap”编解码器无法在位置 0 : character maps to <undefined> MariaDB and SQLAlchemy 处对字符 '\u010c' 进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69946299/

相关文章:

mysql group by column1,column2 'Desc\|asc' 没有报错

python - 负前瞻正则表达式贪婪(为什么.*?太贪婪)

python - SQLAlchemy 邻接列表 - 约束 Parent_id 不等于 ID

mysql - 获取一些行和总数的存储过程

database - 将字典插入sqlite3

python - SQLAlchemy 在连接到 SQL Azure 时挂起,但并非总是挂起

mysql - InnoDB 清除 mariadb 进程列表中的 worker

python - 确定字节顺序的最 Pythonic 方式是什么?

python - 使用 Python 查找顶级 Twitter 好友

python - 在存在条件的数据库中查找非唯一值