python用法:处理sqlite中的中文字符时遇到的问题

本文探讨了使用Python操作SQLite3数据库时遇到的字符编码问题。通过对比不同文件编码方式(UTF-8与ANSI)下的程序行为,揭示了如何正确处理中文字符,确保数据的正确插入与查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作为初学才,学起python,是挺快,但是也不免常常出些小错。在访问sqlite3的时候,我写了下边的测试代码。

文件test.py是utf-8编码的,OK,结果没问题。

#!/usr/bin/envpython
#
coding=utf-8

importsqlite3

#con=sqlite3.connect(r"sqlite.db")
con=sqlite3.connect(r"e: estsqlite3.db")
#con.text_factory=str
cur=con.cursor()
#cur.execute("insertintobasvslvoy(vslcode,voyage,vslename)values(?,?,?)",(u'tt',u'tt',u'tt'))
cur.execute("insertintot1values(?,?)",(10,u'中文测试gbk10'))
con.commit()
cur.execute(u
"select*fromt1wherecol2like'中%'")
forrowincur.fetchall():
printrow[0],row[1].encode('gbk')

con.close()

结果如下:

Processstarted>>>
10中文测试gbk10
10中文测试gbk10
5
10中文测试gbk10
10中文测试gbk10
10中文测试gbk10
10中文测试gbk10
10中文测试gbk10
10中文测试gbk10
10中文测试gbk10
10中文测试gbk10<<<Processfinished.

可是,当我把文件编码调整成ansi格式的时候,上边程序没办法跑。
结果将文件内容改成下边的样子:

#!/usr/bin/envpython
#
coding=utf-8

importsqlite3

#con=sqlite3.connect(r"sqlite.db")
con=sqlite3.connect(r"e: estsqlite3.db")
#con.text_factory=str
cur=con.cursor()
#cur.execute("insertintobasvslvoy(vslcode,voyage,vslename)values(?,?,?)",(u'tt',u'tt',u'tt'))
cur.execute("insertintot1values(?,?)",(10,'中文测试gbk10'.decode('gbk')))
con.commit()
cur.execute(
"select*fromt1wherecol2like'"+''.decode('gbk')+"%'")
forrowincur.fetchall():
printrow[0],row[1].encode('gbk')


con.close()

这样,出现的结果跟上边一样。
问题的关键就是#coding=utf-8,同时文件编码也要是utf-8,才能让结果保持一致。
看看下边的简单例子就知道:

>>>a='中文'
>>>b=u'中文'
>>>a
'ÖÐÎÄ'
>>>b
u
'中文'
>>>a.decode('gbk')
u
'中文'
>>>b==a.decode('gbk')
True

如果将上边的例子放到一个.py文件当中,分别采用utf-8编码和ansi编码('cp936'),结果可能就是分别为True和False。


<script type="text/javascript"><!-- google_ad_client = "ca-pub-7104628658411459"; /* wide1 */ google_ad_slot = "8564482570"; google_ad_width = 728; google_ad_height = 90; //--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值