Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2395879
  • 博文数量: 328
  • 博客积分: 4302
  • 博客等级: 上校
  • 技术积分: 5486
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-01 11:14
个人简介

悲剧,绝对的悲剧,悲剧中的悲剧。

文章分类

全部博文(328)

文章存档

2017年(6)

2016年(18)

2015年(28)

2014年(73)

2013年(62)

2012年(58)

2011年(55)

2010年(28)

分类: Python/Ruby

2013-11-09 19:02:55

分析一个字符串,并更新数据库的时候,出现了如下错误:
'latin-1' codec can't encode character u'\u017e' in position 11: ordinal not in range(256)

进行了一些研究发现,原因是,数据库的编码和数据源的编码不一致,并且包含了不能处理的字符。

有两种方法可用,一个是先预先处理一下字符串,二是设置数据库参数

1. 处理字符串
  1. >>> u = u'hello\u2013world'
  2. >>> u.encode('latin-1', 'replace') # replace it with a question mark
  3. 'hello?world'
  4. >>> u.encode('latin-1', 'ignore') # ignore it
  5. 'helloworld'

  6. 或者根据需求进行处理

  7. >>> u.replace(u'\u2013', '-').encode('latin-1')
  8. 'hello-world'
  9. If you aren't required to output Latin-1, then UTF-8 is a common and preferred choice. It is recommended by the W3C and nicely encodes all Unicode code points:

  10. >>> u.encode('utf-8')
  11. 'hello\xe2\x80\x93world
2. 设置数据库
  1. db.set_character_set('utf8')
  2. dbc.execute('SET NAMES utf8;')
  3. dbc.execute('SET CHARACTER SET utf8;')
  4. dbc.execute('SET character_set_connection=utf8;')

阅读(3387) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~