sqlite介绍
SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。
它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口。
比起Mysql、PostgreSQL这两款开源的世界著名数据库管理系统来讲,它的处理速度比他们都快。
SQLite第一个Alpha版本诞生于2000年5月。 至今已经有14个年头,SQLite也迎来了一个版本 SQLite 3已经发布。
不像常见的客户-服务器范例,SQLite引擎不是个程序与之通信的独立进程,而是连接到程序中成为它的一个主要部分。所以主要的通信协议是在编程语言内的直接API调用。
这在消耗总量、延迟时间和整体简单性上有积极的作用。
整个数据库(定义、表、索引和数据本身)都在宿主主机上存储在一个单一的文件中。它的简单的设计是通过在开始一个事务的时候锁定整个数据文件而完成的。
使用技巧
1、从www.sqlite.org下载一个sqlite,它是一个嵌入式数据库,没有服务器的概念,windows版的就是一个exe,自己把它放到一个合适的目录里,然后把这个目录加入系统的path变量.
建立数据库:
XP版本:sqlite3.exe test.db
Linux版本:./sqlite3.bin test.db
2、然后去找个pysqlite,这是python访问sqlite的接口,地址在这里 : http://initd.org/tracker/pysqlite
目前针对不同的python版本,pysqlite有两个版本:2.3和2.4,请根据自己的python版本选用.
3、然后就可以打开自己喜欢的编辑器,写一段测试代码了.
4、中文处理要注意的是sqlite默认以utf-8编码存储.
5、另外要注意sqlite仅支持文件锁,换句话说,它对并发的处理并不好,不推荐在网络环境使用,适合单机环境;
用Python操作sqlite数据库
import pysqlite2.dbapi2 as sqlite
def runTest():
cx = sqlite.connect(test.db)
cu = cx.cursor()
#create
cu.execute(create table catalog(
id integer primary key,
pid integer,
name varchar(10) unique
))
#insert
cu.execute(insert into catalog values(0,0,"www.ttlsa.com"))
cu.execute(insert into catalog values(1,0,"hello"))
cx.commit()
#select
cu.execute(select * from catalog)
print 1:,
print cu.rowcount
rs = cu.fetchmany(1)
print 2:,
print rs
rs = cu.fetchall()
print 3:,
print rs
#delete
cu.execute(delete from catalog where id = 1 )
cx.commit()
cu.execute(select * from catalog)
rs = cu.fetchall()
print 4:,
print rs
#select count
cu.execute("select count(*) from catalog")
rs = cu.fetchone()
print 5:,
print rs
cu.execute("select * from catalog")
cu.execute(drop table catalog)
if __name__ == __main__:
runTest()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
importpysqlite2.dbapi2assqlite
defrunTest():
cx=sqlite.connect(test.db)
cu=cx.cursor()
#create
cu.execute(createtablecatalog(
idintegerprimarykey,
pidinteger,
namevarchar(10)unique
))
#insert
cu.execute(insertintocatalogvalues(0,0,"www.ttlsa.com"))
cu.execute(insertintocatalogvalues(1,0,"hello"))
cx.commit()
#select
cu.execute(select *fromcatalog)
print1:,
printcu.rowcount
rs=cu.fetchmany(1)
print2:,
printrs
rs=cu.fetchall()
print3:,
printrs
#delete
cu.execute(deletefromcatalogwhereid=1)
cx.commit()
cu.execute(select *fromcatalog)
rs=cu.fetchall()
print4:,
printrs
#select count
cu.execute("select count(*) from catalog")
rs=cu.fetchone()
print5:,
printrs
cu.execute("select * from catalog")
cu.execute(droptablecatalog)
if__name__==__main__:
runTest()