空间内容仅为个人学习备份所用!

发布新日志

  • python 访问 sqlite 数据库

    2010-06-25 14:55:03

    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仅支持文件锁,换句话说,它对并发的处理并不好,不推荐在网络环境使用,适合单机环境;

    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,"张小山")')
        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()
  • sqlite简明教程

    2010-06-25 14:52:40

    本文的主要目的是作为一个入门级教程,教你一些如何使用PySqlite来操作 Sqite 的一些基本的语句,更详细的还要去参考想应的文档以及编写相应的测试程序。希望本文对你有帮助。

    我以前的Blog sqlite一个轻巧的数据库

    PySqlite的主页地址:http://pysqlite.sourceforge.net/ 上面有关于使用PySqlite的文档

    一、安装

    去PySqlite主页上下载安装包,有windows的版本,现支持 Python 2.2和2.3版本。

    二、创建数据库/打开数据库

    Sqlite使用文件作为数据库,你可以指定数据库文件的位置。

    >>> import sqlite
    >>> cx = sqlite.connect("d:/test.db", encoding='cp936')

    使用sqlite的connect可以创建一个数据库文件,上面我指明了路径。当数据库文件不存在的时候,它会自动创建。如果已经存在这个文件,则打开这个文件。encoding指明保存数据所使用的编码,这里cp936是 Python 中自带的编码,其实就是GBK编码。cx为数据库连接对象。

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

    3.1 数据库连接对象

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

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

     3.2 游标对象

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

    cu = cx.cursor()

    这样定义了一个游标。游标对象有以下的操作:

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

    关于对象的方法可以去 Python 主页上查看DB API的详细文档。不过PySqlite到底支持DB API到什么程序,我就不知道了。我列出的操作都是支持的,不过我不是都使用过。

    四、使用举例

    4.1 建库

    前面已经有了,不再重复。(这些例子,如果你有兴趣,可以直接在Python的交互环境下试试)

    4.2 建表

    >>> cu=cx.cursor()
    >>> cu.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(插入)

    >>> 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(选择)

    >>> cu.execute("select * from catalog")
    >>> cu.fetchall()
    [(0, 0, 'name2'), (1, 0, 'hello')]

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

    >>> cu.execute("select * from catalog where id = 1")
    >>> cu.fetchone()
    (1, 0, 'hello')

    对数据库没有修改的语句,执行后不需要再执行事务语句。

    4.5 update(修改)

    >>> cu.execute("update catalog set name='name2' where id = 0")
    >>> cx.commit()
    >>> cu.execute("select * from catalog")
    >>> cu.fetchone()
    (0, 0, 'name2')

    4.6 delete(删除)

    >>> cu.execute("delete from catalog where id = 1")
    >>> cx.commit()
    >>> cu.execute("select * from catalog")
    >>> cu.fetchall()
    [(0, 0, 'name2')]

    以上是关于如何使用PySqlite来操作Sqlite的简单示例。

    五、后记

    以上都是可以在交互环境下可以运行的,有兴趣可以试一试。现在Sqlite已经升级到3.0.2(beta)了。在我写上一个Blog的时候,我下载的还是2.8.13,变化挺大的了。而且它的主页也进行了改版。

Open Toolbar