海上月明

editer by sun
posts - 162, comments - 51, trackbacks - 0, articles - 8
   :: 首页 :: 新随笔 ::  :: 聚合  :: 管理

python操作sqlite3 碰到中文问题

Posted on 2013-06-07 19:01 pts 阅读(5822) 评论(0)  编辑  收藏 所属分类: Python

错问症状:

OperationalError: Could not decode to UTF-8 column 'shouji_lanshouyuan' with text '国际2部 邬长春'

解决方案:

conn = sqlite3.connection(" ... ")
conn.text_factory = str

解决问题方案来源:http://bbs.csdn.net/topics/250055755

设置python使用什么类型来处理sqlite3的text类型,默认是unicode,所以才会产生
OperationalError: Could not decode to UTF-8 column 'name' with text '国内其他' 
这个错误

因为从数据库中取出数据时,是gbk编码(因为你上次存进去的是gbk)
conn.text_factory的默认值是unicode,python会尝试将text类型的字段转换成unicode,就产生了错误

 

附:sqlite3的row操作:

Row对象的详细介绍

class sqlite3.Row

Row instance serves as a highly optimized row_factory for Connection objects. It tries to mimic a tuple in most of its features.

It supports mapping access by column name and index, iteration, representation, equality testing and len().

If two Row objects have exactly the same columns and their members are equal, they compare equal.

Changed in version 2.6: Added iteration and equality (hashability).

keys()

This method returns a tuple of column names. Immediately after a query, it is the first member of each tuple in Cursor.description.

New in version 2.6.

    下面举例说明

复制代码
cx.row_factory = sqlite3.Row

= cx.cursor()

c.execute('select * from catalog')
 <sqlite3.Cursor object at 0x05666680>

= c.fetchone()

type(r)
<type 'sqlite3.Row'>

r
<sqlite3.Row object at 0x05348980>

print r
(0, 
10, u'\u9c7c', u'Yu')

len(r)
4

r[2]            #使用索引查询
u'\u9c7c'

r.keys()
['id''pid''name''nickname']

 使用列的关键词查询
In [43]: r['id']
Out[43]: 0
In [44]: r['name']
Out[44]: u'\u9c7c'

 


只有注册用户登录后才能发表评论。


网站导航: