我使用python脚本将数据插入sqlite3。但我的问题是脚本正在插入三个重复(相同)的数据。只需插入三次相同的数据。
print flag
if flag == 1:
print colored('Authorized', 'green')
pi1.write(6, 0)
conn1 = sqlite3.connect('db/local.db')
c = conn1.cursor()
i = datetime.datetime.now()
date = i.strftime("%Y-%m-%d %H:%M:%S")
c.execute("INSERT INTO lock_logs (msg,created_at,card,date,host_ip,door_name,state) VALUES ('Authorized card','"+date+"', "+reader_value+", '"+date+"', '"+get_ip_address('eth0')+"', 'NL_1','opened')")
conn1.commit()
conn1.close()
time.sleep(3)
pi1.write(6, 1)
print "inserted"
#cron will send log to server
else:
print colored('Not Authorized', 'red')
pi1.write(6, 1)
#store log to local sqllight file
#conn = sqlite3.connect('db/local.db')
conn2 = sqlite3.connect('db/local.db')
c = conn2.cursor()
i = datetime.datetime.now()
date = i.strftime("%Y-%m-%d %H:%M:%S")
c.execute("INSERT INTO lock_logs (msg,created_at,card,date,host_ip,door_name,state) VALUES ('Not Authorized card','"+date+"', "+reader_value+", '"+date+"', '"+get_ip_address('eth0')+"', 'NL_1','failed')")
conn2.commit()
conn2.close()
#cron will send log to server
print "_____________________________________"
注意:如果section和else部分只执行一次但插入了三个记录而只插入一个。
将数据存入数据库文件(local.db)
545|2017-01-28 20:35:44||Authorized card|43448981|2017-01-28 20:35:44|172.20.100.15|NL_1|opened|0
546|2017-01-28 20:35:44||Authorized card|43448981|2017-01-28 20:35:44|172.20.100.15|NL_1|opened|0
547|2017-01-28 20:35:44||Authorized card|43448981|2017-01-28 20:35:44|172.20.100.15|NL_1|opened|0
如何防止这种自动多次输入?
答案 0 :(得分:1)
根据示例数据,时间戳和卡ID在多个条目中重复。您可以在这两个字段上创建唯一性索引,这将阻止将多个条目插入数据库。
CREATE UNIQUE INDEX index_card_and_created_at_on_lock_logs ON lock_logs(card, created_at);
此唯一性索引将拒绝复制这两个字段的条目。