娟斌心 发表于 2016-12-1 11:13:35

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

  作为初学才,学起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,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,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。
页: [1]
查看完整版本: python用法:处理sqlite中的中文字符时遇到的问题