游标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 对象的更多相关文章

  1. 从FrameworkElement对象创建Cursor对象

    原文:从FrameworkElement对象创建Cursor对象 Normal 0 false false false EN-US ZH-CN X-NONE MicrosoftInternetExpl ...

  2. android中cursor对象的使用

    cursor对象是使用行来存储数据的,你要使用它获得数据,就必须知道每一列的数据名称以及他的数据类型才能获得对象数据 常见的方法: .close()关闭资源:记住,所有的资源对象使用完成后都要主动关闭 ...

  3. Android遍历SqlLite cursor对象:

    //1. Cursor c =...; for(c.moveToFirst(); ! c.isAfterLast(); c.moveToNext()){ //c… } //2. Cursor curs ...

  4. [Android Pro] 完美Android Cursor使用例子(Android数据库操作)

    reference to : http://www.ablanxue.com/prone_10575_1.html 完美 Android Cursor使用例子(Android数据库操作),Androi ...

  5. Android笔记——关于Cursor类的介绍

    使用过 SQLite数据库的童鞋对 Cursor 应该不陌生,加深自己和大家对Android 中使用 Cursor 的理解. 关于 Cursor 在你理解和使用 Android Cursor 的时候你 ...

  6. python实践3:cursor() — 数据库连接操作

    python 操作数据库,要安装一个Python和数据库交互的包MySQL-python-1.2.2.win32-py2.5.exe,然后我们就可以使用MySQLdb这个包进行数据库操作了. 操作步骤 ...

  7. Android sqlite cursor的遍历

    查询并获得了cursor对象后,用while(corsor.moveToNext()){}遍历,当corsor.moveToNext()方法调用,如果发现没有对象,会返回false public Li ...

  8. Android Cursor空指针的问题

    最近几天无聊自己动手写个音乐播放器,用到Cursor来取得数据库中音乐文件的信息,但是当用到Cursor的时候总是报空指针错误,后来发现是模拟器上没有音乐文件,使用Cursor的时候 ,若Cursor ...

  9. Android中Cursor(游标)类的概念和用法

    使用过 SQLite 数据库的童鞋对 Cursor 应该不陌生,如果你是搞.net 开发你大可以把Cursor理解成 Ado.net 中的数据集合相当于dataReader.今天特地将它单独拿出来谈, ...

随机推荐

  1. Asp.NET之对象学习

    一.总述 二.具体介绍 1.Request对象 Request对象是用来获取client在请求一个页面或传送一个Form时提供的全部信息,这包含可以标识浏览器和用户的HTTP变量,存储在client的 ...

  2. 创建FTP服务

    Step1: Create a FTP folder in your C disk, named “AutomationReport” Step2:  Install IIS components. ...

  3. ALSA声卡驱动中的DAPM详解之五:建立widget之间的连接关系

    前面我们主要着重于codec.platform.machine驱动程序中如何使用和建立dapm所需要的widget,route,这些是音频驱动开发人员必须要了解的内容,经过前几章的介绍,我们应该知道如 ...

  4. [JSOI 2010] 满汉全席

    [题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=1823 [算法] 2-SAT [代码] #include<bits/stdc++ ...

  5. 利用【监听器】动态加载Log4j配置文件

    转自:https://veromca273.iteye.com/blog/1889304 1 创建监听器: public class LogListener implements ServletCon ...

  6. E20170621-hm

    detroit  底特律 giant   n. 巨人,大汉; 巨兽,巨物; 卓越人物 woo    vt. 求爱,求婚; 争取…的支持; convince   vt. 使相信,说服,使承认; 使明白; ...

  7. El Dorado(dp)

    http://acm.hdu.edu.cn/showproblem.php?pid=2372 题意:给出n个数,求长度为m的递增子序列的数目. 思路:状态转移方程 dp[i][j] = sum(dp[ ...

  8. 解决Sublime Text 3 的 Package Control 启动失败问题

    今天在使用Sublime Text的时候,需要了这样的情况         遇到这个问题的时候   我是这样解决的 一. 首先 找到 Package Control的下载地址1  下载地址2.将下载下 ...

  9. Linux搭建tomcat文件服务器

    Linux搭建tomcat文件服务器 Linux下配置Tomcat服务器和Windows下其实差不多,可以去官网下载安装包释放或者在线下载,只是当时下载的windows.zip文件,现在下载.tar. ...

  10. redis过期策略和内存淘汰机制

    目录 常见的删除策略 redis使用的过期策略:定期删除+惰性删除 定期删除 惰性删除 为什么要采用定期删除+惰性删除2种策略呢? redis内存淘汰机制 常见的删除策略 1.定时删除:在设置键的过期 ...