【问题标题】:The C# using statement, SQL, and SqlConnectionC# using 语句、SQL 和 SqlConnection
【发布时间】:2011-03-05 23:30:08
【问题描述】:

这可以使用 using 语句 C# SQL 吗?

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}

如果打开连接时出错怎么办?

using语句是try and finally
没抓到

那么,如果我在 using 括号外捕获,捕获会捕获连接打开错误吗?

如果没有,如何使用上面显示的using 语句来实现?

【问题讨论】:

    标签: c# sql using-statement


    【解决方案1】:

    在 C# 中可以这样做(我还看到代码完全显示在 MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx 中)。但是,如果您需要采取防御措施,例如记录有助于在生产环境中进行故障排除的潜在异常,您可以采用以下方法:

    private static void CreateCommand(string queryString,
    string connectionString)
    {
        using (SqlConnection connection = new SqlConnection(
               connectionString))
        {
            try
            {
                SqlCommand command = new SqlCommand(queryString, connection);
                command.Connection.Open();
                command.ExecuteNonQuery();
            }
            catch (InvalidOperationException)
            {
                //log and/or rethrow or ignore
            }
            catch (SqlException)
            {
                //log and/or rethrow or ignore
            }
            catch (ArgumentException)
            {
                //log and/or rethrow or ignore
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果您想捕获任何错误,则需要将所有内容包装在 try - catch 块中。 using 块只是确保释放非托管资源,它们无法处理异常。

      另外,SqlCommand 实现了IDisposable,所以我建议也将它放在using 块中。

      【讨论】:

        【解决方案3】:

        只要明确写出来:

        SqlConnection connection = new SqlConnection(connectionString);
        try
        {
            using (SqlCommand command = new SqlCommand(queryString, connection))
            {
                command.Connection.Open();
                command.ExecuteNonQuery();
            }
        }
        catch (Exception e)
        {
            // ...handle, rethrow. Also, you might want to catch
            // more specific exceptions...
        }
        finally
        {
            connection.Close();
        }
        

        【讨论】:

        • 怎么不呢?这就是在 using 块中使用 SqlConnection 最终会调用的内容。
        • 一些逻辑问题对吗?发生捕获,然后处理好捕获并最终起作用。但是如果没有发生错误怎么办? connection opens-work done-using 隐式关闭连接,然后最后也尝试关闭关闭的连接!错误.....对吗?
        • 不。在这两种情况下(使用“使用”,并明确地写出来)最终块将被调用。导致 SqlConnection.Close() 被调用。
        • 仍然不需要手动操作using;那可能只是try { using(var connection = new SqlConnection(connectionString) {...} } catch (Exception e) {...} - 不需要finally / 显式connection.Close()
        • 同意,这只是我个人在这种情况下首选的编写方式(try-catch-finally);它很好地排列了IMO。但对每个人来说,当然。轻点:真的吗?对 2010 年提出并回答的问题的评论?
        【解决方案4】:

        是的,您可以将using 块放入try 块中,以下catch 将捕获与try 块相关的任何错误。

        【讨论】:

          【解决方案5】:

          为字段添加唯一索引到数据库并捕获错误。

          不要为每一行重新实例化 SQL 连接。打开和关闭连接是资源密集型的。试试这样的:

          protected void btn_insert_Click(object sender, EventArgs e)
          {
              string connStr = "your connection string";
              SqlCommand cmd;
          
              using (SqlConnection con = new SqlConnection(connStr))
              {
                  con.Open();
                  foreach (GridViewRow g1 in GridView1.Rows)
                  {
                      try
                      {
                          cmd = new SqlCommand("command text", con);
                          cmd.ExecuteNonQuery();
                      }
                      catch (SqlException sqlEx)
                      {
                          //Ignore the relevant Sql exception for violating a sql unique index
                      }
                  }
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-05-07
            • 1970-01-01
            • 2011-09-17
            • 1970-01-01
            • 1970-01-01
            • 2010-11-23
            • 2011-09-26
            相关资源
            最近更新 更多