С#与System.Data.SQLite - 关闭连接
问题描述:
林清楚地意识到,我应该做这样的SELECT查询:С#与System.Data.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 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 hanging.I不能从GenericSelect方法内关闭它,因为这意味着它总是返回空的DataReader或错误,我无法从外面关闭它。 任何建议,我应该怎么办GenericSelect妥善所以它使返回的DataReader?
我知道我可以使用的数据表,但除了性能,在很多地方使用这个方法,所以我将节省大量的时间,如果它不断回来,他现在返回了什么。
答
首次定位是
SQLiteDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
并且这根据MSDN
当执行命令时,相关联的连接对象是 当相关联的DataReader对象被关闭关闭。
当然,现在确保打电话给SQLiteDataReader.Close
至关重要。
你GenericSelect方法是'static'所以创建和销毁每次调用该方法时,您的连接。 – banging 2013-05-10 19:29:26
你为什么不返回一个DataTable? – banging 2013-05-10 19:30:21
因为他需要改变每调用GenericSelect程序?因为填充一个DataTable然后在这个循环上有效地将性能命中翻倍? – Steve 2013-05-10 19:37:16