python - sqlalchemy更新数据报错
本文介绍了python - sqlalchemy更新数据报错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
这是我的更新代码
def alter(self,id,key,value):
session = Goods().getsession()
session.query(Goods).filter(Goods.id==id).update({key:value})
session.close()
但是会报错
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)
最新查错。
打印如下
print type(id),type(key),type(value)
<type 'unicode'> <type 'unicode'> <type 'unicode'>
127.0.0.1 - - [31/Mar/2017 06:32:05] "GET /alter?id=1497&key=name&value=%E8%8D%A3%E8%80%80V9+%E6%89%8B%E6%9C%BA+%E9%93%82%E5%85%89%E9%87%91+%E5%85%A8%E7%BD%91%E9%80%9A4G(4G+RAM%2B64G+ROM)%E6%A0%87%E9%85%8D HTTP/1.1" 200 -
初步发现问题所在 数据库为latin1编码
然后封装json的时候
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 90-91: unexpected end of data
代码
def get(self):
session = Goods().getsession()
goodslist = session.query(Goods)
session.close()
data = []
for goods in goodslist:
tmp = {}
tmp['id'] = goods.id
tmp['name'] = goods.name //这里报错根源 带空格
tmp['link'] = goods.link
tmp['price'] = goods.price
tmp['commit'] = goods.commit
data.append(tmp)
jsondata = json.dumps(data) //这里报错
解决方案
没怎么写过,但是猜测一下
1. 确认你的key和value都不为None2. 更新不用commit么
明显是数据库字符集设置有问题,请设置数据库字符集为UTF-8
如果不想设置数据库,就解码待插入的数据 info_str.encode('你的格式')再插入
这篇关于python - sqlalchemy更新数据报错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文