摘要:*sqlchemy中create_engine()的返回的engine默认的charset为latin-1.如果往数据库中插入中文,则会出现乱码。
问题描述“
在使用sqlalchemy的sqlalchemy_core部分插入数据的时候
engine = create_engine(db_uri(AlyMonthBill.__bindkey__), encoding='utf-8',connect_args={"use_unicode":True,"charset":"utf8"})
insert_columns = [{"month":201806,"name":"cdn华北2"}]
engine.execute(
AlyMonthBill.__table__.insert(),
insert_columns
)
这里要注意的是:
encoding默认就是''utf8",这里写出来是为了强调一下。可以在文档中找到默认值说明。
connect_args参数为字典,这里设置数据库连接使用unicode编码,然后字符集为utf8.
如果不这样子设置,当如上的代码中insert_columns包含的中文的时候,就会出现本文标题的错误。
因为这里默认的connect_args的默认编码是latin-1,而latin-1中没有对中文进行编码。
所以使用通用的编码集utf8正确插入中文字符而不出现乱码,因为mysql一般也是用编码集utf8或者是utf8mb4(utf8的扩展)。
参考:
https://stackoverflow.com/questions/3942888/unicodeencodeerror-latin-1-codec-cant-encode-character
https://blog.csdn.net/wanglingxxx/article/details/52049278
https://docs.sqlalchemy.org/en/rel_1_1/core/engines.html#custom-dbapi-args
另外设置connection的charset也可以如下:
# 设置connection的chatset-方法二
e = create_engine(
"mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")