我的 SQLite 代碼有問題。我試圖檢查我的 SQLite 表中是否存在一條記錄,但由于某種原因,它總是回傳 -1,無論該記錄是否存在。據我所知,如果記錄存在,它應該回傳 1,如果不存在,它應該回傳 0。有人可以指出我的錯誤嗎?謝謝!
var freeHours = new List<DateTime>();
User user = new User();
for (int i = user.HoursOfWork[0]; i < user.HoursOfWork[1]; i )
{
DateTime hour = new DateTime(date.Year, date.Month, date.Day, i, 0, 0);
int exist;
using (var con = new SQLiteConnection(cs))
using (var comm = new SQLiteCommand("SELECT EXISTS(SELECT 1 FROM Schedule WHERE date = @date)", con))
{
comm.Parameters.AddWithValue("@date", hour.ToString());
con.Open();
exist = comm.ExecuteNonQuery();
}
if(exist != 1) //The object doesn't exists in the DB
{
freeHours.Add(hour);
}
}
uj5u.com熱心網友回復:
當您希望回傳某些資料時,不應使用 ExecuteNonQuery。它是一整套行或只是一個標量值。
與 SELECT 陳述句一起使用時,ExecuteNonQuery 將始終回傳 -1。至少這是微軟對其實作所說的,不確定這是否與 SQLite 相同。
對于 UPDATE、INSERT 和 DELETE 陳述句,回傳值是受命令影響的行數。對于所有其他型別的陳述句,回傳值為 -1。
在您的背景關系中,當您期望單個 SCALAR 值時,您可以使用 ExecuteScalar
exist = (int)comm.ExecuteScalar();
強制轉換是必要的,因為 ExecuteScalar 回傳一個物件
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344057.html
上一篇:這是否違反了開放/封閉原則?
下一篇:如何獲得第二個逗號的索引?
