通过使用语句和Dispose为DataTable,SqlConnection,SqlCommand和SqlDataAdapter清理资源

我必须调用存储过程并获得结果。 我知道有很多方法可以做到这一点(与所有编程一样),我应该通过调用Dispose()和/或Close()来清理资源。 阅读这篇文章或处理问题我认为我应该使用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; } 

PS – 我知道我可以调用ExecuteScalar ,但这不是我在这里寻找的,因为我将使用非标量调用的通用格式。

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

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

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

您可以将using语句“链接”到这样:

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