class sqlite3.Cursor
本类定义了Cursor对象,主要有以下的属性和方法:
execute(sql[, parameters])
执行一个SQL语句。此SQL语句可以通过参数parameters进行替换。
例子:
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table people (name_last, age)")
who = "Yeltsin"
age = 72
# This is the qmark style:
cur.execute("insert into people values (?, ?)", (who, age))
# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
print(cur.fetchone())
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),) # this is a 1-tuple
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
theIter = IterChars()
cur.executemany("insert into characters(c) values (?)", theIter)
cur.execute("select c from characters")
print(cur.fetchall())
也可以使用产生器方式,例子:
import sqlite3
import string
def char_generator():
for c in string.ascii_lowercase:
yield (c,)
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
cur.executemany("insert into characters(c) values (?)", char_generator())
cur.execute("select c from characters")
print(cur.fetchall())
executescript(sql_script)
非标准的一次性地执行多条SQL语句。
例子:
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.executescript("""
create table person(
firstname,
lastname,
age
);
create table book(
title,
author,
published
);
insert into book(title, author, published)
values (
'Dirk Gently''s Holistic Detective Agency',
'Douglas Adams',
1987
);
""")
fetchone()
获取下一行查询数据返回,返回一个序列结果,或者没有数据时返回None。
fetchmany(size=cursor.arraysize)
获取下一批查询数据返回,如果有数据返回一个列表结果集,否则返回一个空列表。每次调用返回的数量由参数size大小决定。
fetchall()
获取所有查询数据返回,返回一个列表。
rowcount
统计数据库里所有行已经发生变化的行数。
lastrowid
只读属性,返回最后修改的行ID。
description
只读属性,返回最后查询的列名称。
蔡军生 QQ:9073204 深圳