我使用的模式看起來像這樣經常。我想知道這是否正常,或者是否有我不在這裏申請的最佳做法。當引發異常時,確保SQL連接關閉的正確方法是什麼?
具體我想知道;在引發異常的情況下,我在finally塊中的代碼足以確保連接適當關閉?
public class SomeDataClass : IDisposable
{
private SqlConnection _conn;
//constructors and methods
private DoSomethingWithTheSqlConnection()
{
//some code excluded for brevity
try
{
using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection))
{
_SqlConnection.Open();
countOfSomething = Convert.ToInt32(cmd.ExecuteScalar());
}
}
finally
{
//is this the best way?
if (_SqlConnection.State == ConnectionState.Closed)
_SqlConnection.Close();
}
//some code excluded for brevity
}
public Dispose()
{
_conn.Dispose();
}
}
呃......你爲什麼要檢查的連接關閉之前已經關閉?爲什麼使用類成員來存儲連接,如果你要使用它的唯一方法關閉它? – Shog9 2008-09-26 18:46:33
spoon16包含短語「//爲了簡潔排除某些代碼」。由此我推斷這不是使用它的唯一方法。 – 2008-09-26 18:52:41
是正確的,這絕對是我能想到的最簡單的例子。我認爲,由於連接池,我不需要嘗試存儲每個方法範圍之外的SqlConnection對象。所以只要使用USING作爲其他建議。 – 2008-09-26 20:19:35