我查看了一些不同的建议,但是由于某些原因,以下解决方案均无法正常工作/仍在表中重复数据。
“类别”将是此SQLite表的唯一值。要更改的值为“ spending_limit”。
到目前为止,我已经尝试过:
public void writeToSpendingLimits(int sequence, double amount){
String sql = "INSERT OR REPLACE INTO spending_limits(category, spending_limit) "
+ "VALUES(" + sequence + ", " + amount + ");";
connection.executeSQL(sql);
}
。
public void writeToSpendingLimits(int sequence, double amount){
String sql = "INSERT INTO spending_limits (category, spending_limit) "
+ "VALUES(" + sequence + ", " + amount + ") "
+ "ON CONFLICT(category)"
+ "DO UPDATE SET spending_limit = " + amount + ";";
connection.executeSQL(sql);
。
public void writeToSpendingLimits(int sequence, double amount){
String sql = "INSERT INTO spending_limits (category, spending_limit) "
+ "VALUES (coalesce((select category from spending_limits where category = " + amount + "),"
+ "(select max(category) from spending_limits) + 1), " + amount + ");";
connection.executeSQL(sql);
。
public void writeToSpendingLimits(int sequence, double amount){
String sql = "UPDATE spending_limits "
+ "SET category = " + sequence + ", " + "spending_limit = " + amount + " "
+ "WHERE spending_limit = " + sequence + ";\n"
+ "INSERT INTO spending_limits(category, spending_limit) "
+ "SELECT " + sequence + ", " + amount + " "
+ "WHERE (Select Changes() = 0)";
connection.executeSQL(sql);
答案 0 :(得分:0)
假设您要为每个类别设置单个支出限额,则可以将类别设为 UNIQUE 列。然后,重复的类别将导致冲突,并且将执行冲突操作,例如 OR REPLACE
。
例如考虑以下:-
DROP TABLE IF EXISTS spending_limits;
CREATE TABLE IF NOT EXISTS spending_limits (category INTEGER UNIQUE NOT NULL, spending_limit REAL);
INSERT OR REPLACE INTO spending_limits (category, spending_limit) VALUES(1,10.23);
INSERT OR REPLACE INTO spending_limits (category, spending_limit) VALUES(2,10.23);
INSERT OR REPLACE INTO spending_limits (category, spending_limit) VALUES(3,10.23);
INSERT OR REPLACE INTO spending_limits (category, spending_limit) VALUES(4,10.23);
INSERT OR REPLACE INTO spending_limits (category, spending_limit) VALUES(5,10.23);
INSERT OR REPLACE INTO spending_limits (category, spending_limit) VALUES('Animal',10.23);
INSERT OR REPLACE INTO spending_limits (category, spending_limit) VALUES('Vegetable',10.23);
INSERT OR REPLACE INTO spending_limits (category, spending_limit) VALUES('Mineral',10.23);
SELECT *,rowid AS rid FROM spending_limits;
INSERT OR REPLACE INTO spending_limits (category, spending_limit) VALUES(1,11.23);
INSERT OR REPLACE INTO spending_limits (category, spending_limit) VALUES('Animal',11.23);
SELECT *,rowid AS rid FROM spending_limits;
这将:-
结果是:-
最初插入8行后:-
在插入(替换)具有现有类别的2行之后:-