我正在尝试使用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()
答案 0 :(得分:12)
使用execute()
执行返回数据的查询。
您必须使用循环,或使用IN (id1, id2, id3)
where子句:
cur.execute('SELECT * FROM Genre WHERE id in ({0})'.format(', '.join('?' for _ in ids)), ids)
答案 1 :(得分:2)
您收到的错误消息很简单,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