我使用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 "_____________________________________"
注意:If节和else节只执行一次,但插入了三条记录,而不是只插入一条记录。在
将数据采样到数据库文件中(本地.db)
^{pr2}$如何防止这种自动多次输入?在
基于示例数据,时间戳和卡id在多个条目中重复。您可以为这两个字段的唯一性创建索引,这将防止将多个条目插入数据库。在
此唯一性索引将拒绝这两个字段重复的条目。在
相关问题 更多 >
编程相关推荐