linzkkk 发表于 2014-12-02 18:10

python用sqlite中文乱码问题

用python测试了一下sqlite,从txt读取数据插入sqlite,结果在sqlite表里面显示乱码,从sqlite取出来在python显示又正常,求高手解释一下什么情况。编码应该怎么设置

#_*_coding:gb18030_*_
    try:
      cn = sqlite3.connect('sqlite.db')
      f = open('E:/jquery/数据库test/data/data.txt','r')
      cn.text_factory = str   
      cur = cn.cursor()
      for line in f:
            s = line.split('|')
            cur.execute('insert into userinfoss values(?,?,?,?)',(s,s,s,s))
    except Exception,e:
      print e
    cn.commit()
    cur.close()
    cn.close()

Northland 发表于 2014-12-04 22:19

sqlite数据库默认使用utf-8编码

你使用的data.txt文件一般情况下是使用的gbk或者类似编码

在写入数据库的时候转换一下编码:

insert into userinfoss values(?,?,?,?)',(s.decode('gbk').encode(utf-8'),s.decode('gbk').encode(utf-8'),s.decode('gbk').encode(utf-8'),s.decode('gbk').encode(utf-8'))

当你从sqlite读出内容需要显示的时候,可以再转换回来:   s0 = s0.decode('utf-8').encode('gbk') ,(对于支持utf-8文本显示的编辑器不需要进行转换)

linzkkk 发表于 2014-12-05 10:36

可以了,非常感谢!回复 2# Northland


   

linzkkk 发表于 2014-12-05 14:14

还有一个问题,我像下面这样从dos输入中文来查就不行了
            name = str(raw_input('要查找的人>'))         
            if name == '0':break
            cur.execute('select * from userinfoss where a1 = ?' , (name.decode('gbk').encode('utf-8')))
这样提示:
cur.execute('select * from userinfoss where a1 = ?' , (name.decode('gbk').encode('utf-8')))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 9 supplied.

这个是什么错误呢?
回复 2# Northland


   
页: [1]
查看完整版本: python用sqlite中文乱码问题