2014-05-14 18 views
0

我正在爲我的應用程序使用ASP.Net WebserviceApplication,它正在與我的SQL Server進行通信。應該在所有用戶的sql事務之後關閉SQLConnection還是應該每次打開?我應該關閉SQLConnection對於Webservice中的所有事務嗎?

例如;

public void Connection() 
    { 
     if (connection == null) 
      connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString()); 

     if (connection.State == ConnectionState.Closed) 
      connection.Open(); 
     else if (connection.State == ConnectionState.Broken) 
     { 
      connection.Close(); 
      connection.Open(); 
     } 
    } 

    [WebMethod] 
    public long GetUsersRankMonthly(string userName) 
    { 
     Connection(); 
     SqlCommand command = new SqlCommand("Select scores.Rank From (SELECT ROW_NUMBER() OVER(ORDER BY Score DESC) AS Rank,Score,NickName,ID FROM teatalay.TopScoresGeneral) scores Where UserName = @userName", connection); 
     command.Parameters.Add(new SqlParameter("@userName", userName)); 

     var result = (long?)command.ExecuteScalar(); 

     return result.HasValue ? result.Value : -1; 
    } 

謝謝。

回答

3

使用sql命令時,將使用語句中的事務換行。讓ASP.NET負責SQL連接池。它比你的代碼更精緻一些。儘可能保持精簡,只有在注意到服務器的連接數量是性能問題的根源時才進行修改。

編輯

using (var cnn = new SqlConnection("connection string here")){ 
    using (var cmd = new SqlCommand("SProc or parametized text", cnn)){ 
     cnn.Open(); 
     // do stuff 
     cnn.Close(); 
    } 
} 
+0

請問您能給我最好的做法嗎? –

+0

@TuğrulEmreAtalay最好的做法是根據需要打開連接,然後在'using'塊中關閉它。當您關閉連接時,它不會實際關閉,但會返回到「[連接池](http://msdn.microsoft.com/zh-cn/library/8xx3tyca%28v=vs.110%29.aspx) 「因此,如果連接重新打開,它可以重新使用。 –

+0

謝謝@Josh –

1

通常,當處理連接,最好使用using而且塊

if (connection.State == ConnectionState.Closed) 

不guarranty,它會打開你的連接,因爲你可能會在ConnectionState.Connecting

使用聲明保證它會在完成時關閉你的連接:

public long GetUsersRankMonthly(string userName) 
    { 
    connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString()); 
    using (connenction) 
     { 
     connenction.Open(); 
     SqlCommand command = new SqlCommand("Select scores.Rank From (SELECT ROW_NUMBER() OVER(ORDER BY Score DESC) AS Rank,Score,NickName,ID FROM teatalay.TopScoresGeneral) scores Where UserName = @userName", connection); 
     using (command) 
     { 
     .......... 
     ...... 
     } 
     }      

    } 
相關問題