SqlConnection,SqlCommand并且SqlDataReader都实现了IDisposable界面.我读到了一个总是包装IDisposables成using块的最佳实践.
因此,我查询数据的常见场景看起来就像这样(在更大的上下文中,像linq2sql这样的映射工具是合适的,但我们假设我们想在这里使用这种方法):
using (SqlConnection cn = new SqlConnection("myConnectionstring"))
{
using (SqlCommand cm = new SqlCommand("myQuery", cn))
{
// maybe add sql parameters
using (SqlDataReader reader = cm.ExecuteReader())
{
// read values from reader object
return myReadValues;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是正确的方式还是被认为是矫枉过正?我对这种嵌套using块有点不确定,但当然我想以正确的方式做到这一点.谢谢!