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

Python中SQLite数据库使用初步

2014-03-30 10:59 309 查看
Sqlite是一个轻量级的数据库,类似于Access.
一、 安装

Python 2.5开始提供了对sqlite的支持,带有sqlite3库.

没有sqlite的版本需要去PySqlite主页上下载安装包.

PySqlite下载地址http://code.google.com/p/pysqlite/downloads/list 

二、创建数据库/打开数据库
Sqlite使用文件作为数据库,你可以指定数据库文件的位置。 

[python] view
plaincopy

import sqlite3 #导入模块  

cx = sqlite3.connect("d:\\test.db")  

#这个是建立在内存里, 内存中的任何操作都不需要commit
#cx = sqlite3.connect(':memory:') 

使 用sqlite的connect可以连接一个数据库文件,当数据库文件不存在的时候,它会自动创建。如果已经存在这个文件,则打开这个文件。cx为数据库连接对象。 

三、操作数据库的基本对象
3.1 数据库连接对象 

象前面的cx就是一个数据库的连接对象,它可以有以下操作: 

         commit()--事务提交 
         rollback()--事务回滚 
         close()--关闭一个数据库连接 
         cursor()--创建一个游标 

3.2 游标对象 所有sql语句的执行都要在游标对象下进行。 

cu = cx.cursor()#这样定义了一个游标。

游标对象有以下的操作: 

        execute()--执行sql语句 
        executemany--执行多条sql语句 
        close()--关闭游标 
        fetchone()--从结果中取一条记录 
        fetchmany()--从结果中取多条记录 
        fetchall()--从结果中取出多条记录 
        scroll()--游标滚动 

四、使用举例
4.1 建库 

[python] view
plaincopy

import sqlite3 #导入模块  

cx = sqlite3.connect("d:\\test.db")  

4.2 建表 

[python] view
plaincopy

cu=cx.cursor()   

u.execute("""create table catalog ( id integer primary key, pid integer, name varchar(10) UNIQUE )""")  

上面语句创建了一个叫catalog的表,它有一个主键id,一个pid,和一个name,name是不可以重复的。 

关于sqlite支持的数据类型,在它主页上面的文档中有描述,可以参考:Version 2 DataTypes.

4.3 insert(插入) 

[python] view
plaincopy

cu.execute("insert into catalog values(0, 0, 'name1')")   

cu.execute("insert into catalog values(1, 0, 'hello')")   

cx.commit()  

如果你愿意,你可以一直使用cu游标对象。注意,对数据的修改必须要使用事务语句:commit()或rollback(),且对象是数据库连接对象,这里为cx。 

4.4 select(选择) 

[python] view
plaincopy

cu.execute("select * from catalog")   

print cu.fetchall()  

[(0, 0, 'name1'), (1, 0, 'hello')]
fetchall() 返回结果集中的全部数据,结果为一个tuple的列表。每个tuple元素是按建表的字段顺序排列。注意,游标是有状态的,它可以记录当前已经取到结果的 第几个记录了,因此,一般你只可以遍历结果集一次。在上面的情况下,如果执行fetchone()会返回为空。这一点在测试时需要注意。 

[python] view
plaincopy

cu.execute("select * from catalog where id = 1")   

print cu.fetchone()   

(1, 0, 'hello')
对数据库没有修改的语句,执行后不需要再执行事务语句。 

4.5 update(修改) 

[python] view
plaincopy

cu.execute("update catalog set name='name2' where id = 0")   

cx.commit()   

cu.execute("select * from catalog")   

print cu.fetchone()   

(0, 0, 'name2')
4.6 
delete(删除) 

[html] view
plaincopy

 cu.execute("delete from catalog where id = 1")   

 cx.commit()   

 cu.execute("select * from catalog")   

 cu.fetchall()   

#cu.close()  

#cx.close()   

[(0, 0, 'name2')]
原文参考: http://www.cnblogs.com/luckeryin/archive/2009/09/25/1574152.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息