C# 带System.Data.SQLite的C-关闭连接
我很清楚我应该这样做:C# 带System.Data.SQLite的C-关闭连接,c#,sqlite,C#,Sqlite,我很清楚我应该这样做: 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 someth
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_保持不变。我不能从GenericSelect方法内部关闭它,因为这意味着它将始终返回空数据读取器或错误,我不能从外部关闭它。
有什么建议我应该如何正确地进行GenericSelect以使它不断返回datareader吗
我知道我可以使用datatable,但除了性能之外,这种方法在很多地方都使用,因此如果它继续返回他现在返回的内容,我将节省大量时间。第一个修复方法是
SQLiteDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
这是根据
执行该命令时,关联的连接对象为
关闭关联的DataReader对象时关闭
当然,现在最重要的是确保调用SQLiteDataReader.Close 您的GenericSelect方法是静态的,因此每次调用该方法时都会创建和销毁连接。为什么不返回一个DataTable?因为他需要更改调用GenericSelect的每个过程?因为填充一个数据表,然后循环,有效地将性能提高了一倍?我想是的,但我经常使用它时会遇到数据库锁定错误。所以,使用它之后,连接可能会很好并且很活跃。