在sqlite中更新

cvxl0en2  于 2023-08-06  发布在  SQLite
关注(0)|答案(2)|浏览(118)

我试图插入或替换一个退出记录内sqlite,但如果记录被发现,它被完全取代,但我希望int值递增。

INSERT OR REPLACE INTO persons (id, username, points, score) VALUES ('id', 'username', 10, 2)

字符串
如果记录存在,我希望能够获取现有的点和水平,并添加到他们与新的值传入,我怎么做?我卡住了

ldioqlga

ldioqlga1#

这就像在Python中更新字典一样。如果记录不存在,则创建它,否则更新它。

cur.execute('SELECT COUNT(*) FROM persons WHERE id=?;', (id,))
if cur.fetchone()[0] == 0:
    # Record does not exist.
    cur.execute('INSERT INTO persons (id, username, points, score) VALUES (?,?,?,?);', (id,username,points,score)
else:
    # Record exists.
    cur.execute('UPDATE persons SET points=points+?, score=score+? WHERE id=?;', (points,score,id))

字符串

c2e8gylq

c2e8gylq2#

自版本3.24.0起,SQLite支持UPSERT

sql = """
  INSERT INTO persons (id, username, points, score) VALUES (?, ?, ?, ?)
  ON CONFLICT(id) DO UPDATE
  SET points = points + EXCLUDED.points,
      score = score + EXCLUDED.score;
"""
cur.execute(sql, (id, username, points, score))

字符串
假设id是唯一的,这将起作用。
参见demo

相关问题