首页 > 编程 > Python > 正文

python使用sqlite3时游标使用方法

2020-02-22 23:27:15
字体:
来源:转载
供稿:网友

cursor就是一个Cursor对象,这个cursor是一个实现了迭代器(def__iter__())和生成器(yield)的MySQLdb对象,这个时候cursor中还没有数据,只有等到fetchone()或fetchall()的时候才返回一个元组tuple,才支持len()和index()操作,这也是它是迭代器的原因。但同时为什么说它是生成器呢?因为cursor只能用一次,即每用完一次之后记录其位置,等到下次再取的时候是从游标处再取而不是从头再来,而且fetch完所有的数据之后,这个cursor将不再有使用价值了,即不再能fetch到数据了。

数据库支持

使用简单的纯文本只能实现有退限的功能,所需要引入数据库,完成更强大功能,本节使用的简单数据库SQLite 。

SQLite 和PySQLite

sqlite是非常著名的开源嵌入式数据库软件,它可以嵌入到其他程序中使用,并且提供SQL接口用来查询,非常方便。它的官方站点为http://www.sqlite.org。

而pysqlite 则是一个sqlite 为 Python 提供的 api 接口,它让一切对于 sqlite 的操作都变得异常简单

在python2.5版本这后,SQLite的优势在于它的一个包装(PySQLite)已经被包括在标准库内,所以我们可以直接使用。

入门操作

可以将SQLite作为名为sqlite3的模块导入。之后就可以创建一个到数据库文件的连接—-如果文件不存在就会被创建—-通过提供一个文件名:

>>> import sqlite3>>> conn= sqlite3.connect('somedatabase.db') # 创建数据库>>>cu =conn.cursor() #能获得连接的游标

创建数据表

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

插入两条数据

>>>cu.execute("insert into catalog values(0,0,'name1')")>>>cu.execute("insert into catalog values(1,0,'name2')")>>>conn.commit()

选择(select)

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

修改(update)

>>>cu.execute(“update catalog set name='name2′ where id = 0″)>>> cx.commit()>>> cu.execute(“select * from catalog”)>>> cu.fetchone()(0, 0, ‘name2′)

删除(delete)

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

连接

为了使用基础数据库系统,首先必须连接到它,这个时候需要使用具有名称的connect函数,该函数有多个参数,而具体用哪个参数取决于数据库。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表