ADO.NET和不使用的处理

时间:2012-03-01 22:47:26

标签: ado.net dispose

我有一个项目没有在其任何地方使用其ADO.NET代码。我正在清理他们未被封闭的连接。下面的代码是try / catch / finally的最佳实践。我也有一些包含我在命令和连接配置之间处理的SqlTransaction。

SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyNGConnectDashBoardConnectionString"].ToString());
            SqlCommand cmd = new SqlCommand();
            DataSet ds = new DataSet();
            try
            {
                con.Open();
                cmd.Connection = con;

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);

            }
            catch (Exception ex)
            {
                throw ex;
            }

            finally
            {
                cmd.Dispose();
                con.Dispose();
            }

3 个答案:

答案 0 :(得分:1)

实际上,使用SqlDataAdapter.Fill(dataset)方法时无需担心关闭连接。此方法在执行每次填充后关闭连接。

此外,无需调用SqlCommand.Dispose(),因为命令本身没有非托管资源可以清理。您应该关注的是在某个时刻调用SqlConnection.Close()。这是在填充后完成的。

答案 1 :(得分:0)

最佳做法是使用using而不是try / finally:)

但是在您的情况下,即使使用也不需要,因为Fill()关闭了连接:

        SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyNGConnectDashBoardConnectionString"].ToString())
        SqlDataAdapter da = new SqlDataAdapter("your sql is here", con);
        da.Fill(ds);

同样简单的重新抛出异常毫无意义。如果您需要记录错误,只需使用普通throw;作为@Cory建议。

答案 2 :(得分:0)

你有什么好。处置使用非托管资源的对象始终是个好主意。但是,如果你厌倦了总是明确地调用Dispose,那么最佳做法可能是使用using

using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyNGConnectDashBoardConnectionString"].ToString()))
{
    using (SqlCommand cmd = new SqlCommand())
    {
        DataSet ds = new DataSet();
        try
        {
            con.Open();
            cmd.Connection = con;

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);

        }
        catch (Exception ex)
        {
            throw; // I changed this too!
        }
    }
}

此外,如果你要“重新抛出”异常,你几乎总是想要throw。如果throw ex;,则会丢失一些堆栈跟踪。