Sqlite: Insert if not exist, Update if exist

前端 未结 2 343
自闭症患者
自闭症患者 2021-01-21 07:12

I have a database with 2 tables like this:

cg_resp
id  | name   | email
1   | George | george@yahoo.com

id column is primary

相关标签:
2条回答
  • 2021-01-21 07:25

    SQLite has no built-in mechanism that would not delete the existing row.

    The easiest way to do this is to put the logic into your application:

    cursor = db.execute("SELECT ...")
    if cursor.empty:
        db.execute("INSERT ...")
    else:
        db.execute("UPDATE ...")
    

    If your language allows to read the number of affected rows, it is possible to do this with two SQL commands:

    db.execute("UPDATE ...")
    if db.rowcount == 0:
        db.execute("INSERT ...")
    
    0 讨论(0)
  • 2021-01-21 07:39

    Use INSERT OR REPLACE which does exactly what you want : insert a new row when the name does not exists or update otherwise.

    0 讨论(0)
提交回复
热议问题