如何強行關閉數據庫連接?企業庫5.0強行關閉活動連接
我使用創建連接的示例代碼:
class Customer{
private readonly Database _db;
public Customer(){
_db = = DatabaseFactory.CreateDatabase(_userSettings.ConnstringName);
}
.. stuff to use this connection..
}
如何強行關閉數據庫連接?企業庫5.0強行關閉活動連接
我使用創建連接的示例代碼:
class Customer{
private readonly Database _db;
public Customer(){
_db = = DatabaseFactory.CreateDatabase(_userSettings.ConnstringName);
}
.. stuff to use this connection..
}
把代碼(..東西使用此連接..)一using
塊,這將確保關閉連接裏面。例如:
using (DbCommand command = _db.GetStoredProcCommand(sprocName, parameters))
{
和:
using (IDataReader rdr = _db.ExecuteReader(command))
{
Using塊是確保資源的一個很好的方式正確關閉:
using語句允許 程序員指定對象時 那些使用資源應該釋放 他們。
否則,您必須顯式調用Close()
方法連接對象上:
if (command.Connection.State == ConnectionState.Open)
command.Connection.Close();
我不能這樣做,因爲我沒有創建連接。由** cmd = _db.GetStoredProcCommand(query)**或** _ db.Get..SomeThing **或** _db._db.ExecuteReader/ExecuteDatase ** – Akhil 2011-04-19 14:01:09
使用**你是對的。我只是更新了代碼片段以反映真正的EL語法。使用塊的好處是重點。 – 2011-04-19 14:05:20
另一件事是,當對象(這種情況下,客戶)得到處置所有資源消耗的對象(可能是連接)得到處置(連接得到關閉..)我正確..? – Akhil 2011-04-19 14:15:00
與工作有關它的全部源代碼示例任何最終的解決方案? – Kiquenet 2013-10-30 08:37:02