python - SQLite3 Python : executemany SELECT

标签 python select sqlite executemany

我正在尝试使用 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()

最佳答案

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

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

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

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

关于python - SQLite3 Python : executemany SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14142554/

相关文章:

python - pytz 美国/东部来回转换时间戳

mysql - 大查询 : how to retrieve values in field 1 corresponding to field 2

sql - 帮我重写这个查询

database - Qt 对 SQLite 的存储查询更快吗?

javascript - 同步 Sequelize 模型 : sequelize. import() 不是函数(并且已弃用)

swift - 如何隐藏 SQLite 数据库文件以便在 iTunes 文件共享中看不到它们

python - 根据 img.shape 值将图像移动到文件夹

python - 如何在 python 中停止服务器?

python - 哪个标准异常类用于违反协议(protocol)?

javascript - NgSelect 未在选择中选择选项