Ala*_*an2 8 .net c# sqlite xamarin xamarin.forms
我有这两个陈述:
db2.Execute(" UPDATE CLICKHISTORY SET " +
" DAYOFYEAR = " + dayOfYear + " , " +
" YEAR = " + year + " , " +
" MONTH = " + month + " , " +
" DAY = " + day + " , " +
" BTNACOUNT = BTNACOUNT + 1 WHERE YYMMDD = " + yymmdd );
db2.Execute(" INSERT INTO CLICKHISTORY " +
" (YYMMDD,DAYOFYEAR,YEAR,MONTH,DAY,BTNACOUNT) " +
" VALUES ( " +
yymmdd + " , " +
dayOfYear + " , " +
year + " , " +
month + " , " +
day + " , " +
"1) WHERE changes() = 0");
Run Code Online (Sandbox Code Playgroud)
我想要做的是在运行第二个语句之前检查第一个语句中是否change()= 0.
任何人都可以告诉我如何将这两个语句组合成一个,以便我可以检查changes()的值吗?
假设db2是类型SQLite.SQLiteConnection,您可以使用方法的返回值Execute来查找受影响的行数 - 类似于:
int rowsAffected = db2.Execute("UPDATE...");
if (rowsAffected == 0) {
rowsAffected = db2.Execute("INSERT...");
}
Run Code Online (Sandbox Code Playgroud)
通常,您可以使用分号组合sqlite语句;.
但据我了解,这里真正的问题是:如何在SQLite中有条件地插入值?
您不能使用WHERE与INSERT INTO table VALUES(...),但使用可以使用INSERT INTO table SELECT ...语法来代替,并添加一个WHERE条款来选择.
假设我有一张简单的表:scores (name varchar(20), score int).如果还没有更新,我想更新一行或插入新行.
var name = "my team";
var sql = $"update scores set score = score+1 where name = '{name}';"
+ $"insert into scores(name, score) select '{name}', 0 where changes() = 0" ;
var cmd = new SQLiteCommand(sql, conn);
cmd.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)
根据您使用的驱动程序,使用的C#方法可能不同 - 我在这里使用System.Data.Sqlite.