【问题标题】:Is it better to create Single or multiple SQL connection to execute same query multiple time?创建单个或多个 SQL 连接以多次执行相同的查询更好吗?
【发布时间】:2016-09-15 10:06:03
【问题描述】:

我每 2 秒执行一次相同的命令。我认为以下代码会创建多个连接:

[System.Web.Services.WebMethod]
public static int getActivity()
{
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString()))
    {
        connection.Open();
        using (var cmd = new SqlCommand("SELECT TOP 1 ValueX FROM TABLE WHERE ID= 2 AND EVENTID = 2 ORDER BY DATE DESC", connection))
        {
            var x = cmd.ExecuteScalar();
            int Result;

            if (x != null)
            {
                Result = int.Parse(x.ToString());
                Console.WriteLine("USER ACTIVITY : " + Result);
            }
            else
            {
                Result = -999;
            }
            connection.Close();
            return Result;
        }
    }
}

如果我多次调用这个方法,下面的代码是多连接还是单连接?

 using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString()))

有人可以解释我是否需要修改此代码还是这个好?

谢谢。

【问题讨论】:

    标签: sql asp.net sql-server database-connection webmethod


    【解决方案1】:

    由于您使用的是using statement 子句,因此一旦您完成该方法,资源就会被释放并关闭连接。所以每次当你调用同一个方法时,都会建立一个新的连接。当您使用 using 子句时,它等效于以下代码:

    SqlConnection connection = null;
    try
    {
        connection = new SqlConnection(connectionString);
    }
    finally
    {
       if(connection != null)
            ((IDisposable)connection).Dispose();
    }
    

    另外请注意,您不需要在方法中显式调用connection.Close();,因为using 语句会处理它。

    【讨论】:

      【解决方案2】:

      您的方法很好,只是不需要 Rahul 所述的connection.Close()。处理 SQL 对象时使用Using 语句是一种很好的做法。

      您应该记住的是,ADO.NET 连接池负责处理引用同一连接字符串的新对象,从而最大限度地减少打开连接所需的时间。

      更多关于connection pooling可以找到Here

      【讨论】:

        猜你喜欢
        • 2011-06-05
        • 1970-01-01
        • 1970-01-01
        • 2016-01-17
        • 1970-01-01
        • 1970-01-01
        • 2020-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多