我试图根据Count和*天来删除SQLite中的行。
而不是像这样编写多个SQL命令:
DELETE * FROM result WHERE Count = 1 AND ("min(_time)" < strftime('%s','now', '-7 day'));
DELETE * FROM result WHERE Count = 2 AND ("min(_time)" < strftime('%s','now', '-14 day'))
DELETE * FROM result WHERE Count = 3 AND ("min(_time)" < strftime('%s','now', '-28 day'));
以此类推...
我正在尝试找到一种用于for循环的方法,该方法可以增加Count和*天
我尝试过:
data = c1.execute('''SELECT * FROM result;''')
for row in data:
Count = row[1]
days = row[7]
c1.execute('''DELETE * FROM result WHERE Count = ? AND ("min(_time)" < strftime('%s','now', '-? day'));''', (Count, days))
我在IndexError: tuple index out of range
下得到一个days = row[7]
。
我抬起error并更改了数字以查看是否可以解决它,但仍然是indexerror。
结果表的样本数据如下所示:“从结果中选择*;”从Splunk导出的列:src_ip,'min(_time)',计数
183.78.180.27|1542266993|1
185.189.150.42|1542246169|1
185.189.150.61|1542271436|1
2002:8672:d515::8672:d515|1537536602|3
150.135.165.114|1537288499|3
我的脚本概念正确吗?关于indexerror有什么建议吗?谢谢!
答案 0 :(得分:1)
考虑参数化整个间隔日期'-7 day'
,'-14 day'
,...,因为不应引用qmark占位符。然后,将构建的字符串传递给.execute()
调用:
delete_sql = '''DELETE FROM result
WHERE [Count] = ?
AND ("min(_time)" < strftime('%s', 'now', ?));
'''
data = c1.execute("SELECT * FROM ...")
for i in data.fetchall():
Count = i[0]
days = '-{} day'.format(i[7])
c1.execute(delete_sql, (Count, days))
conn.commit()
答案 1 :(得分:1)
问题:我正在尝试寻找一种用于for循环的方法,该方法可以增加Count和* days
增加Count
和days
:
day = -7
for count in range(1, 4):
print("WHERE Count = {} AND '{} day')".format(count, day))
day = day * 2
输出:
注意:尚未可用于SQL语句!WHERE Count = 1 AND '-7 day') WHERE Count = 2 AND '-14 day') WHERE Count = 3 AND '-28 day')
经过Python:3.5.3
的测试