如何在Python / Django中使用准备好的语句插入多个SQLite记录?

32 投票
2 回答
46328 浏览
提问于 2025-04-16 15:28

我该如何在Python/Django中使用预处理语句来插入多个记录到SQLite数据库里呢?

2 个回答

9

你可以使用 executemany() 方法,并传入一个迭代器对象,比如说用来插入 100 个整数及其平方值:

def my_iter(x):
    for i in range(x):
        yield i, i*i

cursor.executemany("INSERT INTO my_table VALUES (?, ?)", my_iter(100))
53

官方的Python库文档:游标对象

Python的SQLite库没有准备好的语句对象,但它们允许你使用带参数的查询,并且可以提供多个参数集。

编辑:这里有一个executemany的例子,按照要求提供:

values_to_insert = [(1,"foo"), (2, "bar"), (3, "baz")]

cursor.executemany("""
    INSERT INTO some_table ('item_num', 'item_name')
    VALUES (?, ?)""", values_to_insert)

撰写回答