Because SqlCommand
实施IDisposable
,我通常会按如下方式处理 ADO 查询。
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
// Execute command, etc. here
}
但是,如果我需要在单个连接期间执行多个命令怎么办?我真的需要一个新的吗using
每个命令的块?
我从 Microsoft 找到的示例不使用using
阻止SqlCommand
s(或者甚至调用Dispose()
)。关于处置的最佳做法是什么SqlCommand
?
当然,最佳做法是处置它们。
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(query1, connection))
{
// Execute command, etc. here
}
using (SqlCommand command2 = new SqlCommand(query2, connection))
{
// Execute command, etc. here
}
using (SqlCommand command3 = new SqlCommand(query3, connection))
{
// Execute command, etc. here
}
}
MSDN 可能不会显示它,因为它是并不真正需要 https://stackoverflow.com/questions/1808036/is-sqlcommand-dispose-required-if-associated-sqlconnection-will-be-disposed的情况下SqlCommand
。但在我看来,微软不在每个实现的对象上使用这种模式是不好的IDdisosable
因为人们还不习惯它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)