【问题标题】:Properly parameterize sqlite query with IN operator [duplicate]使用 IN 运算符正确参数化 sqlite 查询 [重复]
【发布时间】:2017-02-15 01:59:59
【问题描述】:

我想从记录 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')]

【问题讨论】:

  • 大声笑@“感觉像失败”;-)

标签: python sqlite


【解决方案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)

【讨论】:

  • 我很高兴我对这个答案有所了解,但我不确定我需要多长时间才能找到 IN 声明的 999 项上限进一步阅读该页面!
  • 是的,这绝对是一个正在酝酿中的问题......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2015-01-30
  • 1970-01-01
  • 1970-01-01
  • 2018-01-31
相关资源
最近更新 更多