【问题标题】:How to check if Record exists如何检查记录是否存在
【发布时间】:2017-10-20 19:52:17
【问题描述】:

我希望能够检查数据库中是否存在具有特定“ID”的记录,如果没有则创建一个(即不存在)像这样...... 我还想在更新后获取特定记录的“Num”。

import sqlite3 as lite

db = lite.connect("test.db")
id_to_be_added = "123456789101112"

db.execute("CREATE TABLE USERS (ID TEXT, NUM INT)")

Query = "{ SOMETHING IN SQL }"  # This returns either True or False
if Query:
    db.execute("UPDATE USERS SET NUM = NUM + 1 WHERE ID =  {};".format(id_to_be_added))

else:
    db.execute("INSERT INTO USERS ({}, 0)".format(id_to_be_added))

num_to_be_printed = db.execute("SELECT NUM FROM USERS WHERE ID = {}".format(id_to_be_added))

print("{0} has {1}").format(id_to_be_added, num_to_be_printed)

【问题讨论】:

  • 您的查询必须返回真还是假?是否可以返回 0(即不存在记录)或大于 0(即至少存在一条记录)?
  • 是的,只需要返回一些表明存在记录的指示。
  • 我想把你介绍给Bobby Tables...

标签: python sql python-3.x sqlite


【解决方案1】:

要么创建主键并使用INSERT OR REPLACE 查询,要么使用SELECT 查询。

【讨论】:

    【解决方案2】:

    我能够使用 cur.fetchall() 解决它

    import sqlite3 as lite
    
    db = lite.connect(r"test.db")
    id_tba = r"123456789101112"
    cur = db.cursor()
    cur.execute("SELECT * FROM USERS WHERE ID = {}".format(id_tba))
    
    if len(cur.fetchall()) > 0:
        db.execute("UPDATE USERS SET NUM = NUM + 1 WHERE ID =  {};".format(id_tba))
    else:
        db.execute("INSERT INTO USERS ({}, 0)".format(id_tba))
    
    num_to_be_printed = db.execute("SELECT NUM FROM USERS WHERE ID = {}".format(id_tba))
    print("{0} has {1}").format(id_tba, num_to_be_printed)
    

    【讨论】:

      猜你喜欢
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      相关资源
      最近更新 更多