在“使用”块中是SqlConnection在返回或异常时关闭?

问题描述 投票:129回答:7

第一个问题: 说我有

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    string storedProc = "GetData";
    SqlCommand command = new SqlCommand(storedProc, connection);
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));

    return (byte[])command.ExecuteScalar();
}

连接是否关闭?因为从技术上来说,我们永远不会到达最后一个},就像我们之前的return一样。

第二个问题: 这次我有:

try
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        int employeeID = findEmployeeID();

        connection.Open();
        SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
        command.CommandTimeout = 5;

        command.ExecuteNonQuery();
    }
}
catch (Exception) { /*Handle error*/ }

现在,说在try的某个地方我们得到一个错误,它被抓住了。连接是否仍然关闭?因为我们再次跳过try中的其余代码并直接转到catch语句。

我对using的工作方式有过线性思考吗?即当我们离开Dispose()范围时,using是否只是被调用?

c# using sqlconnection
7个回答
171
投票
  1. 是。

无论哪种方式,当退出使用块时(通过成功完成或错误),它将被关闭。

虽然我认为这样组织会更好,因为要看到将要发生的事情要容易得多,即使对于稍后会支持它的新维护程序员来说也是如此:

using (SqlConnection connection = new SqlConnection(connectionString)) 
{    
    int employeeID = findEmployeeID();    
    try    
    {
        connection.Open();
        SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
        command.CommandTimeout = 5;

        command.ExecuteNonQuery();    
    } 
    catch (Exception) 
    { 
        /*Handle error*/ 
    }
}

44
投票

这两个问题都是。 using语句被编译成try / finally块

using (SqlConnection connection = new SqlConnection(connectionString))
{
}

是相同的

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

编辑:将演员表修复为Disposable http://msdn.microsoft.com/en-us/library/yh598w02.aspx


14
投票

这是我的模板。从SQL服务器中选择数据所需的一切。连接已关闭并处理,并且捕获连接和执行中的错误。

string connString = System.Configuration.ConfigurationManager.ConnectionStrings["CompanyServer"].ConnectionString;
string selectStatement = @"
    SELECT TOP 1 Person
    FROM CorporateOffice
    WHERE HeadUpAss = 1 AND Title LIKE 'C-Level%'
    ORDER BY IntelligenceQuotient DESC
";
using (SqlConnection conn = new SqlConnection(connString))
{
    using (SqlCommand comm = new SqlCommand(selectStatement, conn))
    {
        try
        {
            conn.Open();
            using (SqlDataReader dr = comm.ExecuteReader())
            {
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        Console.WriteLine(dr["Person"].ToString());
                    }
                }
                else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)");
            }
        }
        catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
        if (conn.State == System.Data.ConnectionState.Open) conn.Close();
    }
}

*修订日期:2015-11-09 * 正如尼克的建议;如果太多的括号让你烦恼,那就像这样格式......

using (SqlConnection conn = new SqlConnection(connString))
   using (SqlCommand comm = new SqlCommand(selectStatement, conn))
   {
      try
      {
         conn.Open();
         using (SqlDataReader dr = comm.ExecuteReader())
            if (dr.HasRows)
               while (dr.Read()) Console.WriteLine(dr["Person"].ToString());
            else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)");
      }
      catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
      if (conn.State == System.Data.ConnectionState.Open) conn.Close();
   }

再说一次,如果您在EA或DayBreak游戏中工作,您也可以放弃任何换行符,因为这些只适用于那些必须回来查看您的代码且真正关心的人?我对吗?我的意思是1行而不是23行意味着我是一个更好的程序员,对吧?

using (SqlConnection conn = new SqlConnection(connString)) using (SqlCommand comm = new SqlCommand(selectStatement, conn)) { try { conn.Open(); using (SqlDataReader dr = comm.ExecuteReader()) if (dr.HasRows) while (dr.Read()) Console.WriteLine(dr["Person"].ToString()); else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)"); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } if (conn.State == System.Data.ConnectionState.Open) conn.Close(); }

嗯......好的。我从我的系统中得到了这个,并且我已经做了一段时间。继续。


5
投票

当您离开使用范围时,只会调用Dispose。 “使用”的目的是为开发人员提供有保证的方法来确保资源得到处置。

来自MSDN

当达到using语句的结尾或者抛出异常并且控制在语句结束之前离开语句块时,可以退出using语句。


5
投票

Using围绕被分配的对象生成try / finally,并为您调用Dispose()

它可以省去手动创建try / finally块和调用Dispose()的麻烦


3
投票

在第一个示例中,C#编译器实际上将using语句转换为以下内容:

SqlConnection connection = new SqlConnection(connectionString));

try
{
    connection.Open();

    string storedProc = "GetData";
    SqlCommand command = new SqlCommand(storedProc, connection);
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));

    return (byte[])command.ExecuteScalar();
}
finally
{
    connection.Dispose();
}

最后语句将始终在函数返回之前被调用,因此连接将始终关闭/处置。

因此,在您的第二个示例中,代码将编译为以下内容:

try
{
    try
    {
        connection.Open();

        string storedProc = "GetData";
        SqlCommand command = new SqlCommand(storedProc, connection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));

        return (byte[])command.ExecuteScalar();
    }
    finally
    {
        connection.Dispose();
    }
}
catch (Exception)
{
}

异常将在finally语句中捕获并且连接已关闭。外部catch子句不会看到异常。


1
投票

我在try / catch块中写了两个using语句,如果将它放在内部using语句中,就像ShaneLS example一样,我可以看到异常被捕获了。

     try
     {
       using (var con = new SqlConnection(@"Data Source=..."))
       {
         var cad = "INSERT INTO table VALUES (@r1,@r2,@r3)";

         using (var insertCommand = new SqlCommand(cad, con))
         {
           insertCommand.Parameters.AddWithValue("@r1", atxt);
           insertCommand.Parameters.AddWithValue("@r2", btxt);
           insertCommand.Parameters.AddWithValue("@r3", ctxt);
           con.Open();
           insertCommand.ExecuteNonQuery();
         }
       }
     }
     catch (Exception ex)
     {
       MessageBox.Show("Error: " + ex.Message, "UsingTest", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }

无论放置在哪个try / catch,都会捕获异常而不会出现问题。

© www.soinside.com 2019 - 2024. All rights reserved.