我应该为Web服务中的所有事务关闭SQLConnection吗?

时间:2014-05-14 12:04:46

标签: sql web-services sqlconnection

我正在为我的应用程序使用ASP.Net WebserviceApplication,它正在与我的SQL Server进行通信。我应该在所有用户的sql事务之后关闭SQLConnection还是每次都应该打开它?

例如;

   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;
    }

谢谢。

2 个答案:

答案 0 :(得分:3)

使用sql命令时将事务包装在using语句中。让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();
    }
}

答案 1 :(得分:1)

一般情况下,处理连接时最好使用using

 if (connection.State == ConnectionState.Closed) 

无法保证它会打开您的连接,因为您可能在ConnectionState.Connecting

using语句保证它会在完成时关闭你的连接:

  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)
         {
         ..........
         ......
         }
       }                      

    }