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()
错误是没有出现,不过查询结果的时候发现,中文字符并没有插入进入
![](http://static.oschina.net/uploads/img/201311/12005144_18ac.jpg)
猜测可能还是与字符编码有关系,下载了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 设置
最后结果显示
![](http://static.oschina.net/uploads/img/201311/12005144_YSm9.jpg)
数据录入成功。
后期继续研究python2.6.4下的这个问题~ --- to be continue
相关文章推荐
- OSG+Python
- Python(Tornado)模拟登录小米抢手机
- Python中3元运算符的实现
- python 编码 问题[转]
- python中的参数传递顺序
- python异常基础
- python 元类
- Windows 7 安装64位 Python 2.7.3 开发环境
- python 中生成器的简单介绍及用法
- 运行python脚本的几种方法
- Python类
- Python中import
- python查找算法的实现-二分法
- python记录
- python记录
- [Python下载CSDN博客]1. 简单实现(三)
- Python3实现的腾讯微博自动发帖小工具
- [Python下载CSDN博客]1. 简单实现(二)
- python 笔记
- python排序算法的实现-快速排序