加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

UnicodeEncodeError: 'latin-1' codec can&

发布时间:2020-12-17 16:59:05 所属栏目:Python 来源:网络整理
导读:使用环境: ? ? Mysql和MySQLdb驱动程序 MySql连接数据库方式: engine?=?create_engine("mysql://root:root@localhost/sdy",?echo=True)Session?=?sessionmaker(bind=engine)session?=?Session() 出现地方: 在写入数据时提示错误: UnicodeEncodeError:?'l

使用环境:

? ? Mysql和MySQLdb驱动程序

MySql连接数据库方式:

engine?=?create_engine("mysql://root:root@localhost/sdy",?echo=True)
Session?=?sessionmaker(bind=engine)
session?=?Session()

出现地方:

在写入数据时提示错误:

UnicodeEncodeError:?'latin-1'?codec?can't?encode?characters?in?position?0-2:?ordinal?not?in?range(256)
UnicodeEncodeError:'latin-1'?codec?can't?encode?characters?in?position?0-1:?ordinal?not?in?range(256)

原因:

MySQLdb驱动程序使用的默认编码是latin-1,它不支持您的字符集。您将需要使用UTF-8(或其他,但UTF-8是最常见的)能够通过MySQLdb与您的数据库通信(请参阅http://docs.sqlalchemy.org/en/rel_0_8/dialects/ mysql.html#unicode)。

解决方法:

engine?=?create_engine("mysql://root:root@localhost/sdy?charset=utf8",?encoding='utf8',?echo=True)
Session?=?sessionmaker(bind=engine)
session?=?Session()

如果使用conn,解决方法是:

conn=?pymysql.connect(host='xxxx',port=3306,user='xxx',passwd='xxx',db='xxxx',charset='utf8')


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读