Sqlite: Insert if not exist, Update if exist

前端 未结 2 342
自闭症患者
自闭症患者 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 ...")
    

提交回复
热议问题