2012-11-12 146 views
0

我有我支持老應用程序,我遇到以下共享的SQLConnection跑:共享連接VS個人

private static SqlConnection cnSQL = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString.ToString()); 
    private static SqlCommand cmdSQL = new SqlCommand(); 

現在這個連接被打開,它需要關閉每次,但它仍然得到了散發性錯誤,我相信這是因爲它被用戶共享(靜態)。我的假設是否正確?我相信在每個需要它的方法中創建一個新的連接會更好,而不是每個類都有一個。或者我可以只提取靜態選項,並保持每頁一個連接,而不必擔心跨用戶污染?

感謝

回答

1

靜態成員是在您的應用程序的實際實例中的代碼的所有對象和方法之間共享的,但在之間不存在不同用戶之間的

我會使連接字符串靜態,但不是連接本身。正如你所說,在每種方法中打開一個新的連接。連接池將確保物理連接保持開放。

public static readonly string ConnectionString connString = 
    ConfigurationManager.ConnectionStrings["SQL"].ConnectionString.ToString(); 

...

private void SomeMethod() 
{ 
    using (var conn = new SqlConnection(connString)) { 
     string sql = "SELECT ..."; 
     using (var cmd = new SqlCommand(sql, conn)) { 
      ... 
     } 
    } 
} 

確保您嵌入代碼using -statements。這樣資源即使在發生異常時也會被釋放。

+0

是一個使用需要時,嘗試與最後關閉連接? – Limey

+0

'using'語句被實現爲'try-finally'語句併爲您關閉連接!即它在finally部分調用Dispose(),然後關閉連接。在任何情況下都會發生這種情況,即使您將using語句與「return」分開也是如此。如果你需要一個try-statement用於錯誤處理,並且正在用'finally'部分關閉連接,因爲不需要額外的'using'。 –

1

static肯定可以使不好的事情發生,如果你試圖在同一時間執行兩個查詢。

創建的每個地方,你使用它,Dispose在年底將是我最好的架構方法,一個新的連接。我還會用工廠方法封裝SqlConnection的創建。

3

擺脫兩者並宣佈&定義它們,當你需要他們。

using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString.ToString())) 
{ 
    using (var cmd = conn.CreateCommand()) 
    { ... } 
} 

this answer一讀。

0

先生我擔心在調用execute函數之前應該啓動連接,並且在執行後立即關閉,無論結果是否失敗。如果您在合適的時間關閉和處理分配的資源,則無論是否爲靜態都無關緊要。啓動連接的最佳模式是以下代碼:

SqlCommand command = new SqlConnection("[The connection String goes here]").CreateCommand(); 

try 
{ 
    command.Parameters.Add(new SqlParameter() { ParameterName = "ParameterA", Direction = ParameterDirection.Input, Value = "Some value" }); 

    command.Parameters.Add(new SqlParameter() { ParameterName = "ReturnValue", Direction = ParameterDirection.ReturnValue }); 

    command.CommandText = "[YourSchema].[YourProcedureName]"; 

    command.CommandType = CommandType.StoredProcedure; 

    command.Connection.Open(); 

    command.ExecuteNonQuery(); 
} 
catch (Exception ex) 
{ 
    //TODO: Log the exception and return the relevant result. 
} 
finally 
{ 
    if (command.Connection.State != ConnectionState.Closed) 

     command.Connection.Close(); 

    SqlConnection.ClearPool(command.Connection); 

    command.Connection.Dispose(); 

    command.Dispose(); 
} 

希望它有幫助。

乾杯

+0

爲什麼選擇投票?哪裏不對? – Rikki

+0

不確定爲什麼某個人下了評分,但ClearPool應該完成嗎?難道我不應該讓連接池獨自一人,讓它自己處理? – Limey

+0

我沒有downvote,但在finally部分中調用Dispose()會在關閉連接時執行所有必須完成的操作。 –