9

我正在尝试使用 executemany 函数将所有行从具有一些 WHERE 约束的一行中取出

import sqlite3

con = sqlite3.connect('test.db')
cur = con.cursor()

cur.execute('CREATE TABLE IF NOT EXISTS Genre (id INTEGER PRIMARY KEY, genre TEXT NOT NULL)')

values = [
        (None, 'action'),
        (None, 'adventure'),
        (None, 'comedy'),
        ]


cur.executemany('INSERT INTO Genre VALUES(?, ?)', values)

ids=[1,2]

cur.executemany('SELECT * FROM Genre WHERE id=?', ids)

rows = cur.fetchall()
print rows

错误

cur.executemany('SELECT * FROM Genre WHERE id=?', ids)
sqlite3.ProgrammingError: You cannot execute SELECT statements in executemany()
4

2 回答 2

17

用于execute()执行返回数据的查询。

您要么必须使用循环,要么使用IN (id1, id2, id3)where 子句:

cur.execute('SELECT * FROM Genre WHERE id in ({0})'.format(', '.join('?' for _ in ids)), ids)

上面的表达式为每个项目插入一个单独的?占位符ids(用逗号分隔)。

于 2013-01-03T16:07:52.547 回答
5

您收到的错误消息很简单,You cannot execute SELECT statements in executemany()

只需更改您executemany的执行:

ids=[1,2]
for id in ids:
    cur.execute('SELECT * FROM Genre WHERE id=?', id)
    rows = cur.fetchall()
    print rows
于 2013-01-03T16:10:17.563 回答