如何使用Python防止SQLite3中的多个条目(重复)

2024-10-05 10:17:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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}$

如何防止这种自动多次输入?在


Tags: 数据ipdbdatetimedatelocalconnectcard
1条回答
网友
1楼 · 发布于 2024-10-05 10:17:07

基于示例数据,时间戳和卡id在多个条目中重复。您可以为这两个字段的唯一性创建索引,这将防止将多个条目插入数据库。在

CREATE UNIQUE INDEX index_card_and_created_at_on_lock_logs ON lock_logs(card, created_at);

此唯一性索引将拒绝这两个字段重复的条目。在

相关问题 更多 >

    热门问题