當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python sqlite3.Cursor.executemany用法及代碼示例

用法:

executemany(sql, seq_of_parameters)

針對序列 seq_of_parameters 中找到的所有參數序列或映射執行參數化 SQL 命令。 sqlite3 模塊還允許使用迭代器產生參數而不是序列。

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())

con.close()

這是一個使用生成器的簡短示例:

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())

con.close()

相關用法


注:本文由純淨天空篩選整理自python.org大神的英文原創作品 sqlite3.Cursor.executemany。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。