8.1.2 Cursor 对象

  游标Cursor也是sqlite3模块中比较重要的一个类,下面简单介绍下Cursor对象的常用方法。

  1 execute(sql[,parameters])

  该方法用于执行一条SQL语句,下面的代码演示了用法,以及为SQL语句传递参数的两种方法,分别使用问号好命名变量作为占位符。

 1 import sqlite3
 2 
 3 conn = sqlite3.connect('example.db')
 4 cur = conn.cursor()
 5 cur.execute('create table people(name_last,age)')
 6 who = 'Dong'
 7 age = 38
 8 
 9 #使用问号做占位符
10 cur.execute('insert into people values(?,?)',(who,age))
11 conn.commit()
12 #使用命令变量做占位符
13 cur.execute('select * from people where name_last = :who and age = :age',{"who":who,"age":age})
14 print(cur.fetchone())     #('Dong', 38)
15 conn.close()

  2 executemany(sql,seq_of_parameters)

  该方法用来对于所有给定参数执行用一个SQL语句,参数序列可以使用不同的方式产生,例如下面的代码使用迭代来产生参数序列:

 1 import sqlite3
 2 
 3 #自定义迭代器,按顺序生成小写字母
 4 class IterChars:
 5     def __init__(self):
 6         self.count = ord('a')
 7 
 8     def __iter__(self):
 9         return self
10 
11     def __next__(self):
12         if self.count > ord('z'):
13             raise StopIteration
14         self.count += 1
15         return (chr(self.count - 1),)
16 
17 
18 conn = sqlite3.connect(':memory:')
19 cur = conn.cursor()
20 cur.execute('create table characters(c)')
21 
22 #创建迭代器对象
23 theIter = IterChars()
24 
25 #插入记录,每次插入一个英文小写字母
26 cur.executemany('insert into characters(c) values(?)',theIter)
27 conn.commit()
28 #读取并显示所有记录
29 cur.execute('select * from characters')
30 
31 #读取并显示所有记录
32 print(cur.fetchall())
33 conn.close()

  

  下面的代码则使用了更为简洁的生成器来产生参数:

猜你喜欢

转载自www.cnblogs.com/avention/p/8964829.html