如果记录存在,如何增加数量列,否则插入记录?

时间:2015-02-22 20:58:17

标签: sqlite

我有以下的sqlite数据库:

CREATE TABLE `test` (
    `idx`   INTEGER PRIMARY KEY AUTOINCREMENT,
    `qty`   INTEGER,
    `brand` TEXT,
    `type`  TEXT
);

insert into test (qty, brand, type) values (1, "Merc", "petrol");
insert into test (qty, brand, type) values (1, "Toyota", "diesel");

我想插入另一条记录,但如果它存在,那么我想增加qty字段,所以:

insert into test (qty, brand, type) values (1, "Merc", "diesel");

所以只需将qty字段增加一个,然后

insert into test (qty, brand, type) values (1, "Merc", "petrol");

会插入新记录。

1 个答案:

答案 0 :(得分:2)

SQLite是一个嵌入式数据库,即它旨在与应用程序一起使用。 最简单的方法是将逻辑放入应用程序中:

db.execute("UPDATE test SET qty = qty + 1 WHERE brand = ? AND type = ?",
           ["Merc", "diesel"])
if db.rows_affected == 0:
    db.execute("INSERT ...")
相关问题