游标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. java调用restful接口的方法

    Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法如下: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring的RestTemplate

  2. STM32:TIMER输出比较模式-PWM

    在自己小板子上移植PWM时候又重新学习了一下,加入两点:1,对各种输出比较模式的学习:2,输出模式时加入中断 先写出函数: //TIM4 PWM部分初始化 //PWM输出初始化 //period:输出 ...

  3. Spark SQL读parquet文件及保存

    import org.apache.spark.{SparkConf, SparkContext} import org.apache.spark.sql.{Row, SparkSession} im ...

  4. Weblogic 启动慢解决方法

      添加 启动参数  :      -Xms256m -Xmx512m -XX:MaxPermSize=256m 原因 : 实际是JVM在Linux下的bug:他想调用一个随机函数,但是取不到. 暂时 ...

  5. codevs4511信息传递(Tarjan求环)

    题目描述 有n个同学(编号为1到n)正在玩一个信息传递的游戏.在游戏里每人都有一个固定的信息传递对象,其中,编号为i的同学的信息传递对象是编号为Ti同学. 游戏开始时,每人都只知道自己的生日.之后每一 ...

  6. memcache缓存系统

    一.缓存系统 静态web页面: 1.在静态Web程序中,客户端使用Web浏览器(IE.FireFox等)经过网络(Network)连接到服务器上,使用HTTP协议发起一个请求(Request),告诉服 ...

  7. IE版本的判断

    var Sys = {};var ua = navigator.userAgent.toLowerCase(); var s;(s = ua.match(/msie ([\d.]+)/)) ? Sys ...

  8. Git 标记操作

    .推送标签: git push origin 标签名 .删除本地标签: git tag -d 标签名 .删除远程标签: git push origin :refs/tags/标签名 例:git pus ...

  9. 【洛谷3546_BZOJ2803】[POI2012]PRE-Prefixuffix(String Hash)

    Problem: 洛谷3546 Analysis: I gave up and saw other's solution when I had nearly thought of the method ...

  10. 【BZOJ3205_洛谷3638】[APIO2013]机器人(动态规划)

    题目: 洛谷3638 分析: 卡了一天的神题--(OrzJumpmelon) 首先预处理出从点\(p\)向\(d\)方向出发最终能到达的点\(nxt[p][d]\).这个可以直接记忆化搜索解决.如果出 ...