我有一个连接到数据库并检索数据表的 SQL 类。我知道 SqlConnection 必须在完成后释放。我知道这可以使用using
块,但是也可以接受Dispose()
在这个类的析构函数中调用?
这是我的代码:
public class SQLEng
{
//Connection String Property
//Must be set to establish a connection to the database
public string ConnectionString{ get; set; }
SqlConnection _Conn;
//Overridden Constructor enforcing the Connection string to be set when created
public SQLEng(string connectionString)
{
ConnectionString = connectionString;
_Conn = new SqlConnection(connectionString);
}
//ensure the SqlConnection is disposed when destructing this object
public ~SQLEng()
{
_Conn.Dispose();
}
//various other methods to get datatables etc...
}
基本上我希望有一个类变量 SqlConnection,而不是在访问数据库的每个方法中实例化 SqlConnection。这是声音练习吗?
你的设计鼓励坚持(大概是开放的)SqlConnection
很长一段时间。最佳实践是在需要之前打开连接,然后在完成后立即释放(关闭和处置)它。
是的,创建新连接会产生一些开销;连接池 http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx减少了大部分处理时间。更糟糕的是在服务器上保持许多连接处于活动状态。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)