gpt4 book ai didi

c# - 关闭记录集后是否必须处理 SqlCommand?

转载 作者:太空宇宙 更新时间:2023-11-03 19:12:23 24 4
gpt4 key购买 nike

好吧,这是微不足道的,但它一直困扰着我。我有这样的代码

oCmd = new SqlCommand("getBooking", oCon); 
oCmd.CommandType = CommandType.StoredProcedure;
oRs = oCmd.ExecuteReader();
do while (oRs.Read()) {
// do stuff
}
oRs.Close();
oCmd.Dispose();

但是我可以像这样将 Dispose 移动到 ExecuteReader 之后吗:

oCmd = new SqlCommand("getBooking", oCon); 
oCmd.CommandType = CommandType.StoredProcedure;
oRs = oCmd.ExecuteReader();
oCmd.Dispose();
do while (oRs.Read()) {
// do stuff
}
oRs.Close();

我已经尝试过了,它有效,但感觉就像我在调皮。这种方法有问题吗?我问是因为通常需要在 do while 中重复使用 SqlCommand 对象,不,我不想创建多个 SqlCommand 对象。

最佳答案

是的,最好在处理完这些元素后立即将其丢弃。重用命令确实没有任何优势,您的代码可能因此变得复杂且难以理解和维护。

最好对它使用using语法:

using (var oCmd = new SqlCommand("getBooking", oCon))
{
oCmd.CommandType = CommandType.StoredProcedure;
using (var oRs = oCmd.ExecuteReader())
{
while (oRs.Read()) {
// do stuff
}
}
}

当您在一次性对象上使用using(实现IDisposable)时,Dispose 方法将调用Close。您可以对 SqlConnection 执行相同的操作。

关于c# - 关闭记录集后是否必须处理 SqlCommand?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19697935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com