您的位置:首页 > 编程语言 > Python开发

python之sqlite

2013-11-12 00:51 701 查看

【转】python之sqlite

最近饶有兴趣的用了下Sqlite数据库。主要做日志分析使用。

刚开始的时候,使用python2.6.4,但是遇到如果插入的记录中有中文,会出现

"ErrorCode:

You must not use 8-bit bytestrings unless you use a text_factory that can

interpret 8-bit bytestrings (like text_factory = str). It is highly recommended

that you instead just switch your application to Unicode

strings."

在邮件列表里询问的时候,得达人指点,与 text_factory =

str有关,在程序中增加了该选项,具体如下:

#-*-coding:utf-8-*-

import sqlite3

class

strSqlite():

def __init__(self):

self.db =

sqlite3.connect('str4.db')

self.db.text_factory = str

self.cur =

self.db.cursor()

#设置为INTEGER PRIMARY

KEY属性相当于自增长类型

self.cur.execute("create table if not exists result (ID INTEGER

PRIMARY KEY,SSJ TEXT,SSY TEXT,RANGE TEXT,VALUE TEXT);")

def

execSQL(self,sql,parm):

try:

self.cur.execute(sql,parm)

self.db.commit()

except

sqlite3.DatabaseError,exc:

error, = exc.args

print "ErrorCode: "+

str(error)

pass

def close(self):

self.db.close()

mySqlite =

strSqlite()

str_test = "测试"

str_test2 =

"test"

mySqlite.execSQL("insert into result(SSJ,SSY,RANGE,VALUE)

values(?,?,?,?)",(str_test,str_test2,str_test2,str_test2))

mySqlite.close()

错误是没有出现,不过查询结果的时候发现,中文字符并没有插入进入



猜测可能还是与字符编码有关系,下载了python3.1进行测试

(据了解3.1的对字符集的问题有很大改善)

import sqlite3

class strSqlite():

def

__init__(self):

self.db = sqlite3.connect('test.db')

self.cur =

self.db.cursor()

self.cur.execute("create table if not exists result (ID

INTEGER PRIMARY KEY,SSJ TEXT,SSY TEXT,RANGE TEXT,VALUE TEXT);")

def

execSQL(self,sql,parm):

try:

self.cur.execute(sql,parm)

self.db.commit()

except sqlite3.DatabaseError:

print("ErrorCode: ")

pass

def

close(self):

self.db.close()

mySqlite = strSqlite()

str_test =

"测试"

str_test2 = "test"

mySqlite.execSQL("insert into

result(SSJ,SSY,RANGE,VALUE)

values(?,?,?,?)",(str_test,str_test,str_test,str_test))

mySqlite.close()

并且去掉了

text_factory = str 设置

最后结果显示



数据录入成功。

后期继续研究python2.6.4下的这个问题~ --- to be continue
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: