Cleaning Up Resources via Using Statement & Dispose for DataTable, SqlConnection, SqlCommand, & SqlDataAdapter

泪湿孤枕 提交于 2019-12-08 08:43:16

问题


I have to call a stored procedure and get the results. I know there are various ways of doing this (as with all programming), and that I should be cleaning up the resources by calling Dispose() and/or Close(). Reading this close or dispose question I'm thinking that I should be using the using statement and that should be enough. Below is how I'm making my call. My question is - am I over complicating this and will this clean up all of the resources?

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. - I know I could call ExecuteScalar, but that's not what I'm looking for here since I will be using the general format for non-scalar calls.


回答1:


The code that you wrote does appear to dispose all objects properly.

What you should be aware of is that disposing a DataTable makes that object unusable, which is not usually the intent with a DataTable. Typically if you are populating a DataTable you intend to keep the data around (cached) for a while, and not discard it within the query method.




回答2:


AFAIK you do not need to wrap the DataTable or the SqlDataAdapter in using blocks, as they do not implement IDisposable.

You can "chain" the using statements toegether like this:

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

}


来源:https://stackoverflow.com/questions/11158602/cleaning-up-resources-via-using-statement-dispose-for-datatable-sqlconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!