search

Home  >  Q&A  >  body text

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)   //这里报错
伊谢尔伦伊谢尔伦2785 days ago653

reply all(1)I'll reply

  • PHPz

    PHPz2017-04-18 10:32:25

    I haven’t written much about it, but I’m guessing

    1. Confirm that neither your key nor value is None
    2. No need to commit when updating?

    1. Obviously there is a problem with the database character set setting. Please set the database character set to UTF-8

    2. If you don’t want to set up a database, decode the data to be inserted info_str.encode('your format') and then insert it

    reply
    0
  • Cancelreply