簡體   English   中英

C#with System.Data.SQLite - 關閉連接

[英]C# with System.Data.SQLite - closing connections

我很清楚我應該這樣做SELECT查詢:

System.Data.SQLite.SQLiteConnection scrsql_con = new System.Data.SQLite.SQLiteConnection("Data Source=db.db;Version=3;New=False;Compress=True;");
scrsql_con.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.CommandText = "Select something FROM something";
cmd.Connection = scrsql_con;
SQLiteDataReader dr = cmd.ExecuteReader();
//reading stuff from datareader...
dr.Close();
scrsql_con.Close();

但是,我的應用程序中有很多SELECT查詢,因此我決定為此創建一個方法。 現在它看起來如下:

public static SQLiteDataReader GenericSelect(String query)
{
        System.Data.SQLite.SQLiteConnection scrsql_con = new System.Data.SQLite.SQLiteConnection("Data Source=SCRdb.db;Version=3;New=False;Compress=True;");
        scrsql_con.Open();
        SQLiteCommand cmd = new SQLiteCommand();
        cmd.CommandText = query;
        cmd.Connection = scrsql_con;
        SQLiteDataReader dr = cmd.ExecuteReader();
         return dr; 
}

但它不是很好,因為它讓scrsql_con掛起。我無法從GenericSelect方法內部關閉它,因為這意味着它將始終返回空的datareader或錯誤,我無法從外部關閉它。 任何建議我應該如何正確地進行GenericSelect,以便它不斷返回datareader?

我知道我可以使用數據表,但除了性能之外,這個方法在很多地方使用,所以如果它不斷返回他現在返回的內容,我會節省很多時間。

第一個修復是

SQLiteDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

這是根據MSDN

執行該命令時,關閉關聯的DataReader對象時將關閉關聯的Connection對象。

當然,確保調用SQLiteDataReader.Close現在至關重要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM