9.5.3 Cursor对象

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  深圳

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

caimouse

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值