8.1.2 Cursor 对象
游标Cursor也是sqlite3模块中比较重要的一个类,下面简单介绍下Cursor对象的常用方法。
1 execute(sql[,parameters])
该方法用于执行一条SQL语句,下面的代码演示了用法,以及为SQL语句传递参数的两种方法,分别使用问号好命名变量作为占位符。
import sqlite3 conn = sqlite3.connect('example.db')
cur = conn.cursor()
cur.execute('create table people(name_last,age)')
who = 'Dong'
age = 38 #使用问号做占位符
cur.execute('insert into people values(?,?)',(who,age))
conn.commit()
#使用命令变量做占位符
cur.execute('select * from people where name_last = :who and age = :age',{"who":who,"age":age})
print(cur.fetchone()) #('Dong', 38)
conn.close()
2 executemany(sql,seq_of_parameters)
该方法用来对于所有给定参数执行用一个SQL语句,参数序列可以使用不同的方式产生,例如下面的代码使用迭代来产生参数序列:
import sqlite3 #自定义迭代器,按顺序生成小写字母
class IterChars:
def __init__(self):
self.count = ord('a') def __iter__(self):
return self def __next__(self):
if self.count > ord('z'):
raise StopIteration
self.count += 1
return (chr(self.count - 1),) conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute('create table characters(c)') #创建迭代器对象
theIter = IterChars() #插入记录,每次插入一个英文小写字母
cur.executemany('insert into characters(c) values(?)',theIter)
conn.commit()
#读取并显示所有记录
cur.execute('select * from characters') #读取并显示所有记录
print(cur.fetchall())
conn.close()
下面的代码则使用了更为简洁的生成器来产生参数:
import sqlite3
import string #包含yield语句的函数可以用来创建生成器对象
def char_generator():
for c in string.ascii_lowercase:
yield(c,) conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("create table characters(c)") #使用生成器对象得到参数序列
cur.executemany('insert into characters(c) values(?) ',char_generator())
conn.commit()
cur.execute('select c from characters')
print(cur.fetchall()) #[('a',), ('b',), ('c',), ('d',), ('e',), ('f',), ('g',), ('h',), ('i',), ('j',),
# ('k',), ('l',), ('m',), ('n',), ('o',), ('p',), ('q',), ('r',), ('s',), ('t',),
# ('u',), ('v',), ('w',), ('x',), ('y',), ('z',)]
下面的代码则使用直接创建的序列作为SQL语句的参数:
import sqlite3
persons = [('Hugo','Boss'),('Calvin','Klein')]
conn=sqlite3.connect(':memory:') #创建表
conn.execute('create table person(firstname,lastname)') #插入数据
conn.executemany('insert into person(firstname,lastname) values(?,?)',persons) #显示数据
for row in conn.execute('select firstname,lastname from person'):
print(row) print('I just deleted',conn.execute('delete from person').rowcount,'rows') '''
('Hugo', 'Boss')
('Calvin', 'Klein')
I just deleted 2 rows
'''
3 fetchone()、fetchmany(size=cursor.arraysize)、fetchall()
这3个方法用来读取数据。假设数据库通过下面的代码创建并插入数据:
import sqlite3 conn = sqlite3.connect(r'D:/addressBook.db')
#创建表
conn.execute('create table addressList(name,sex,phon,QQ,address)')
# 创建游标
cur = conn.cursor() #插入数据
cur.execute('''insert into addressList(name,sex,phon,QQ,address) values('王小丫','女','13888997011','66735','北京市')''')
cur.execute('''insert into addressList(name,sex,phon,QQ,address) values('李莉','女','15808066055','675797','天津市')''')
cur.execute('''insert into addressList(name,sex,phon,QQ,address) values('李星草','男','15912108090','3232099','昆明市')''') #提交事务,把数据写入数据库
conn.commit()
conn.close()
#下面的代码演示了使用fetchall()读取数据的方法:
import sqlite3 conn = sqlite3.connect(r'D:/addressBook.db')
cur = conn.cursor()
cur.execute('select * from addressList') #查询表中所有数据,将查询结果放在游标中 #获取游标中所有的查询结果
li = cur.fetchall()
for line in li:
for item in line:
print(item,end=' ')
print() conn.close() '''
王小丫 女 13888997011 66735 北京市
李莉 女 15808066055 675797 天津市
李星草 男 15912108090 3232099 昆明市
'''
8.1.2 Cursor 对象的更多相关文章
- 从FrameworkElement对象创建Cursor对象
原文:从FrameworkElement对象创建Cursor对象 Normal 0 false false false EN-US ZH-CN X-NONE MicrosoftInternetExpl ...
- android中cursor对象的使用
cursor对象是使用行来存储数据的,你要使用它获得数据,就必须知道每一列的数据名称以及他的数据类型才能获得对象数据 常见的方法: .close()关闭资源:记住,所有的资源对象使用完成后都要主动关闭 ...
- Android遍历SqlLite cursor对象:
//1. Cursor c =...; for(c.moveToFirst(); ! c.isAfterLast(); c.moveToNext()){ //c… } //2. Cursor curs ...
- [Android Pro] 完美Android Cursor使用例子(Android数据库操作)
reference to : http://www.ablanxue.com/prone_10575_1.html 完美 Android Cursor使用例子(Android数据库操作),Androi ...
- Android笔记——关于Cursor类的介绍
使用过 SQLite数据库的童鞋对 Cursor 应该不陌生,加深自己和大家对Android 中使用 Cursor 的理解. 关于 Cursor 在你理解和使用 Android Cursor 的时候你 ...
- python实践3:cursor() — 数据库连接操作
python 操作数据库,要安装一个Python和数据库交互的包MySQL-python-1.2.2.win32-py2.5.exe,然后我们就可以使用MySQLdb这个包进行数据库操作了. 操作步骤 ...
- Android sqlite cursor的遍历
查询并获得了cursor对象后,用while(corsor.moveToNext()){}遍历,当corsor.moveToNext()方法调用,如果发现没有对象,会返回false public Li ...
- Android Cursor空指针的问题
最近几天无聊自己动手写个音乐播放器,用到Cursor来取得数据库中音乐文件的信息,但是当用到Cursor的时候总是报空指针错误,后来发现是模拟器上没有音乐文件,使用Cursor的时候 ,若Cursor ...
- Android中Cursor(游标)类的概念和用法
使用过 SQLite 数据库的童鞋对 Cursor 应该不陌生,如果你是搞.net 开发你大可以把Cursor理解成 Ado.net 中的数据集合相当于dataReader.今天特地将它单独拿出来谈, ...
随机推荐
- linux 统计 文件夹信息
ls -lR|grep "^-"|wc -l Linux 统计某个字符串出现的次数 - ywl925 - 博客园 https://www.cnblogs.com/ywl925/p/ ...
- C - Gr-idian MST
Time limit : 2sec / Memory limit : 256MB Score : 500 points Problem Statement On an xy plane, in an ...
- bzoj 4003 [JLOI2015]城池攻占 —— 左偏树
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4003 其实蛮简单的,首先一个城市只会被其子树中的骑士经过,启发我们 dfs 序用可并堆合并子 ...
- PCB MongoDB 索引
在索引在数据库中非常重要,当然在MongoDB也是一样啦. 一.获取索引 db.ppeflow.getIndexes() 初始化,每个集都默认_id字段为主键objectid,索引名为_id_ 二.创 ...
- Codeforces 766E
题意:给一棵树(1e5),每个节点上有对应权值(0<=ai<=1e6)定义树上两个节点间的距离为路径中节点的异或,求所有节点对间的距离和(包括节点自身也作为节点对,距离为节点权值). 解题 ...
- android ListView,GridView 设置某一项显示位置
在项目中有时会用到,当使用 listview 想让它显示某一项,当它又不在前面的位置,可以 使用 //让某一项显示出来(否则可能不在当前) listview.setSelection(positio ...
- 转 方法区(method) )、栈区(stack)和堆区(heap)之JVM 内存初学
JAVA的JVM的内存可分为3个区:堆(heap).栈(stack)和方法区(method) 堆区: 1.存储的全部是对象,每个对象都包含一个与之对应的class的信息.(class的目的是得到操作指 ...
- linq 分组
var data = from r in listRecords group r by new { r.CampaignId, r.CityId, r.Gift_DistributorId, r.Pr ...
- 正则表达式 \D 元字符
\D元字符可以匹配非数字字符,等价于"[^0-9]". 语法结构: (1).构造函数方式: new RegExp("\\D") (2).对象直接量方式: /\D ...
- Recyclerview点击事件,更新item的UI+更新Recyclerview外的控件
项目中用到了Recyclerview,在第一行代码中学到了一种相对来说简单的点击事件方法,可是这种点击事件是在adapter中写的,没有教怎么更新item的ui和更新Recyclerview之外的控件 ...