是否使用(VAR连接=新的SqlConnection("的ConnectionString"))仍接近/配置上的错误连接?错误、SqlConnection、VAR、Connecti

2023-09-06 19:08:07 作者:爱过就好

我有以下的code

 尝试
{
    使用(VAR连接=新的SqlConnection(Utils.ConnectionString))
    {
        connection.Open();

        使用(VAR CMD =新的SqlCommand(StoredProcedure的连接))
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            VAR sqlParam =新的SqlParameter(id_document,idDocument);
            cmd.Parameters.Add(sqlParam);

            INT结果= cmd.ExecuteNonQuery();
            如果(结果!= -1)
                返回东西;

            //做的东西在这里

            返回别的东西;
        }
    }

    //做一点事
}
赶上(SQLEXCEPTION前)
{
    返回AKA的东西没有工作;
}
 

现在的问题是:是否 VAR连接如果使用括号(之间的一个意想不到的错误发生仍然可以关闭 {} )?

问题是,我的大部分存储过程调用是由这种方式,最近我一直在收到此错误:

  

System.InvalidOperationException:超时时间已到。超时   时间已过之前从池中获取一个连接。本   可能发生,因为所有池连接使用,最大   池大小达到了。

予访问数据库的另一种方法是通过的nHibernate

解决方案

的 using语句(C#参考)

  

using语句确保调用Dispose即使   而您呼叫的对象上的方法发生异常。您可以   通过将对象一试块内实现相同的结果,并   然后调用Dispose在finally块;其实,这是怎样的   using语句是由编译器翻译。在code为例   早前扩展到以下code在编译时(注意是多余的   花括号创建该对象的范围有限):

I have the following code

try
{
    using (var connection = new SqlConnection(Utils.ConnectionString))
    {
        connection.Open();

        using (var cmd = new SqlCommand("StoredProcedure", connection))
        {                            
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            var sqlParam = new SqlParameter("id_document", idDocument);
            cmd.Parameters.Add(sqlParam);

            int result = cmd.ExecuteNonQuery();
            if (result != -1)
                return "something";

            //do something here

            return "something else";
        }
    }

    //do something
}
catch (SqlException ex)
{
    return "something AKA didn't work";
}
针对3000位云架构师的调查 DevOps团队使用的云安全工具有些多

The question is: Does var connection still get closed if an unexpected error happens between the using brackets ({ })?

The problem is that most of my calls to stored procedures are made this way, and recently I have been getting this error:

System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

The other way I access the DB is through nHibernate.

解决方案

using Statement (C# Reference)

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):