<a href="http://www.cnblogs.com/yuxc/archive/2011/08/18/2143606.html">用python进行sqlite数据库操作</a>
简单的介绍
安装与使用
1.导入python sqlite数据库模块
python2.5之后,内置了sqlite3,成为了内置模块,这给我们省了安装的功夫,只需导入即可~
import sqlite3
2. 创建/打开数据库
在调用connect函数的时候,指定库名称,如果指定的数据库存在就直接打开这个数据库,如果不存在就新创建一个再打开。
cx = sqlite3.connect("e:/test.db")
也可以创建数据库在内存中。
con = sqlite3.connect(":memory:")
3.数据库连接对象
打开数据库时返回的对象cx就是一个数据库连接对象,它可以有以下操作:
commit()--事务提交
rollback()--事务回滚
close()--关闭一个数据库连接
cursor()--创建一个游标
关于commit(),如果isolation_level隔离级别默认,那么每次对数据库的操作,都需要使用该命令,你也可以设置isolation_level=none,这样就变为自动提交模式。
4.使用游标查询数据库
我们需要使用游标对象sql语句查询数据库,获得查询对象。 通过以下方法来定义一个游标。
cu=cx.cursor()
游标对象有以下的操作:
execute()--执行sql语句
executemany--执行多条sql语句
close()--关闭游标
fetchone()--从结果中取一条记录,并将游标指向下一条记录
fetchmany()--从结果中取多条记录
fetchall()--从结果中取出所有记录
scroll()--游标滚动
1. 建表
cu.execute("create table catalog (id integer primary key,pid integer,name varchar(10) unique,nickname text null)")
上面语句创建了一个叫catalog的表,它有一个主键id,一个pid,和一个name,name是不可以重复的,以及一个nickname默认为null。
2. 插入数据
请注意避免以下写法:
# never do this -- insecure 会导致注入攻击
pid=200
c.execute("... where pid = '%s'" % pid)
正确的做法如下,如果t只是单个数值,也要采用t=(n,)的形式,因为元组是不可变的。
for t in[(0,10,'abc','yu'),(1,20,'cba','xu')]:
cx.execute("insert into catalog values (?,?,?,?)", t)
简单的插入两行数据,不过需要提醒的是,只有提交了之后,才能生效.我们使用数据库连接对象cx来进行提交commit和回滚rollback操作.
cx.commit()
3.查询
cu.execute("select * from catalog")
要提取查询到的数据,使用游标的fetch函数,如:
in [10]: cu.fetchall()
out[10]: [(0, 10, u'abc', u'yu'), (1, 20, u'cba', u'xu')]
如果我们使用cu.fetchone(),则首先返回列表中的第一项,再次使用,则返回第二项,依次下去.
4.修改
in [12]: cu.execute("update catalog set name='boy' where id = 0")
in [13]: cx.commit()
注意,修改数据以后提交
5.删除
cu.execute("delete from catalog where id = 1")
cx.commit()
6.使用中文
请先确定你的ide或者系统默认编码是utf-8,并且在中文前加上u
x=u'鱼'
cu.execute("update catalog set name=? where id = 0",x)
cu.execute("select * from catalog")
cu.fetchall()
[(0, 10, u'\u9c7c', u'yu'), (1, 20, u'cba', u'xu')]
如果要显示出中文字体,那需要依次打印出每个字符串

in [26]: for item in cu.fetchall():
....: for element in item:
....: print element,
....:
0 10 鱼 yu
1 20 cba xu

7.row类型
row提供了基于索引和基于名字大小写敏感的方式来访问列而几乎没有内存开销。 原文如下:
row对象的详细介绍
<dl></dl>
<dt></dt>
class sqlite3.row
<dd></dd>
changed in version 2.6: added iteration and equality (hashability).
keys()
new in version 2.6.
下面举例说明

in [30]: cx.row_factory = sqlite3.row
in [31]: c = cx.cursor()
in [32]: c.execute('select * from catalog')
out[32]: <sqlite3.cursor object at 0x05666680>
in [33]: r = c.fetchone()
in [34]: type(r)
out[34]: <type 'sqlite3.row'>
in [35]: r
out[35]: <sqlite3.row object at 0x05348980>
in [36]: print r
(0, 10, u'\u9c7c', u'yu')
in [37]: len(r)
out[37]: 4
in [39]: r[2] #使用索引查询
out[39]: u'\u9c7c'
in [41]: r.keys()
out[41]: ['id', 'pid', 'name', 'nickname']
in [42]: for e in r:
....: print e,

使用列的关键词查询
in [43]: r['id']
out[43]: 0
in [44]: r['name']
out[44]: u'\u9c7c'
转载请注明出处:http://www.cnblogs.com/haochuang/ 8年it工作经验,5年测试技术与管理,2年产品与项目管理,曾参与过云计算\云存储\车联网产品研发工作; 业余自媒体人,有技术类垂直微信公众号;如有招聘或求职方面需求,请mail to [email protected] ;或通过 qq:363573922 微博:@念槐聚 联系;