使用IN运算符正确参数化sqlite查询

时间:2017-02-14 17:49:10

标签: python sqlite

我想从记录ID与python列表匹配的表中删除记录。

示例数据:

dbfile = ':memory:'
conn = sqlite3.connect(dbfile)
cur = conn.cursor()
cur.executescript('''BEGIN TRANSACTION;
CREATE TABLE `strat` (
    `Id`    INTEGER NOT NULL,
    `thing1`    TEXT NOT NULL,
    `thing2`    NUMERIC NOT NULL,
    PRIMARY KEY(`Id`)
);
INSERT INTO `strat` (Id,thing1,thing2) 
VALUES (1,'0','delete'),
       (2,'34','delete'),
       (3,'456','delete'),
       (4,'458','keep'),
       (5,'998','keep'),
       (6,'1000','delete'),
       (7,'2001','delete');
COMMIT;''')

cur.execute('''select * from strat'''); cur.fetchall()
#Out[32]: 
#[(1, '0', 'delete'),
 #(2, '34', 'delete'),
 #(3, '456', 'delete'),
 #(4, '458', 'keep'),
 #(5, '998', 'keep'),
 #(6, '1000', 'delete'),
 #(7, '2001', 'delete')]

我在别处处理时找到了要删除的记录的ID。在这里,我想删除ID为1,2,3,6,7

的记录
delete_list = [1,2,3,6,7]

期望的输出:

[(4, '458', 'keep'),
(5, '998', 'keep')]

这不起作用:

cur.execute('''DELETE FROM strat WEHRE Id IN ?''', delete_list)

但是等效的方法在sqlite shell中起作用:

DELETE FROM strat WHERE Id IN (1,2,3,6,7)

我已经使用了循环,这有效,但感觉就像失败一样:

   for id in delete_list:
    cur.execute('''delete from strat where Id = ?''', (id,))
    conn.commit()

cur.execute('''select * from strat'''); cur.fetchall()
#Out[50]: [(4, '458', 'keep'), (5, '998', 'keep')]

1 个答案:

答案 0 :(得分:1)

如果delete_list过长,您可以执行以下操作:

place_holders = ",".join("?"*len(delete_list))
query_string = '''delete from strat where Id in ({})'''.format(place_holders)
cur.execute(query_string, delete_list)