使用Statement&amp ;;清理资源处理DataTable,SqlConnection,SqlCommand和& SqlDataAdapter的

时间:2012-06-22 14:49:31

标签: c# ado.net resources using sqlclient

我必须调用存储过程并获得结果。我知道有很多方法可以做到这一点(与所有编程一样),我应该通过调用Dispose()和/或Close()来清理资源。阅读这个close or dispose问题我认为我应该使用using语句,这应该足够了。以下是我打电话的方式。我的问题是 - 我是否过度复杂化,这将清理所有资源吗?

private Int32 CallStoredProcedure(Int32 Id)
{
    using (var dt = new DataTable())
    {
        using (var conn = new SqlConnection(ConnectionString))
        {
            using (var sqlCmd = new SqlCommand("SEL_StoredProcedure", conn))
            {
                using (var sda = new SqlDataAdapter(sqlCmd))
                {
                    sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
                    sqlCmd.Parameters.AddWithValue("@ID", Id);
                    sqlCmd.Connection.Open();

                    sda.Fill(dt);
                }
            }
        }

        if (dt.Rows.Count == 1)
            return Convert.ToInt32(dt.Rows[0]["IDv2"]);
        else if (dt.Rows.Count > 1)
            throw new Exception("Multiple records were found with supplied ID; ID = " + studentId.ToString());
    }
    return 0;
}

P.S。 - 我知道我可以拨打ExecuteScalar,但这不是我在寻找的,因为我将使用非标量呼叫的一般格式。

2 个答案:

答案 0 :(得分:0)

AFAIK您不需要使用块包装DataTable或SqlDataAdapter,因为它们不实现IDisposable。

您可以将using语句“链接”起来像这样:

using(var conn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand("SEL_storedProcedure", conn))
{

}

答案 1 :(得分:0)

您编写的代码确实可以正确处理所有对象。

您应该注意的是,处理DataTable会使该对象无法使用,而通常使用DataTable的意图。通常,如果要填充DataTable,您打算将数据保持一段时间(缓存),而不是在查询方法中丢弃它。