您的位置:首页技术文章
文章详情页

python - sqlalchemy更新数据报错

浏览:34日期:2022-08-12 16:39:16

问题描述

这是我的更新代码

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.idtmp[’name’] = goods.name //这里报错根源 带空格tmp[’link’] = goods.linktmp[’price’] = goods.pricetmp[’commit’] = goods.commitdata.append(tmp) jsondata = json.dumps(data) //这里报错

问题解答

回答1:

没怎么写过,但是猜测一下

1. 确认你的key和value都不为None2. 更新不用commit么

明显是数据库字符集设置有问题,请设置数据库字符集为UTF-8

如果不想设置数据库,就解码待插入的数据 info_str.encode(’你的格式’)再插入

标签: Python 编程
相关文章: