本文介绍了SQLite3 Python:executemany SELECT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用executemany函数将具有某些WHERE约束的所有行从一张表中取出
I'm trying to get all the rows out of a table in one line with some WHERE constraints using the executemany function
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()
推荐答案
使用execute()
执行返回数据的查询.
Use execute()
to execute a query that returns data.
您要么必须使用循环,要么使用IN (id1, id2, id3)
where子句:
You'll either have to use a loop, or use a IN (id1, id2, id3)
where clause:
cur.execute('SELECT * FROM Genre WHERE id in ({0})'.format(', '.join('?' for _ in ids)), ids)
这篇关于SQLite3 Python:executemany SELECT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!