[英]Basic help with SQLite in C# needed - returning strings or ints from a query
我正在將Microsoft Visual C#2008 Express Edition與SqlLite一起使用。 我可以成功打開數據庫,並使用C#代碼將條目添加到表中。
在檢索數據時,我遇到了一些問題,一直在互聯網上搜索有關如何做這些基本事情的基本教程信息。
這是我的代碼...(在我打開與數據庫的連接后,這里稱為“ conn”):
SQLiteCommand cmd = new SQLiteCommand(conn);
cmd.CommandText = "select myField1,myField2 from myTable where myField3 = '" + tempstring + "';";
cmd.CommandType = CommandType.Text;
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string tmp = reader.GetString(0);
System.Console.WriteLine(" my output = " + tmp);
}
當我執行此操作時...我沒有錯誤,因為在最后一行沒有任何輸出,因此看起來while循環根本沒有執行。
我是這些東西的初學者...我想念的是什么?是否有很好的網絡資源可用來學習這些基本知識? 我對SQL本身很滿意...只是沒有像這樣集成在C#中...
首先,在while (reader.Read());
刪除行尾有害的分號while (reader.Read());
...!
在我看來,這是正確的。 屬性reader.HasRows
是否對您的查詢返回true?
需要注意的一些附帶問題是:
回答有關如何編寫參數化查詢的問題:
cmd.CommandText = "select myField1,myField2 from myTable where myField3 = @tempString;";
SQLiteParameter param = new SQLiteParameter("@tempString");
cmd.Parameters.Add(param);
// you can modify that value without touching the sql statement (which means you could cache the above command)
param.Value = tempstring;
SQLiteDataReader reader = cmd.ExecuteReader();
[...]
SQLite中的參數可以有幾種形式,您可以在這里找到。
有關參數化查詢的更多信息,請參見此處 。
好人,Alex。
除此之外,由於您是從sqlite開始的(可能要從標記中刪除第二個L),請記住,sqlite並不能真正保證數據庫級別的數據類型安全。
並不是為了使您擺脫Sqlite問題,但是如果您對C#中嵌入的Sqlite查詢遇到舒適問題,則可以嘗試將NHibernate與Fluent NHibernate結合使用。 這些技術為數據庫(包括Sqlite)提供了出色的數據訪問機制。
NHibernate向Sqlite的請求非常快,您不必擔心Sqlite的某些特質。 如果您使用NHibernate正確構建了數據訪問層,那么您應該能夠迅速升級到更強大的數據庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.