处置SqlCommand [英] Disposing SqlCommand

查看:89
本文介绍了处置SqlCommand的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 SqlCommand 实现了 IDisposable ,所以我通常会按以下方式处理ADO查询.

Because SqlCommand implements IDisposable, I would normally approach an ADO query as follows.

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
    // Execute command, etc. here
}

但是,如果我需要在单个连接中执行多个命令怎么办?每个命令我真的需要一个新的 using 块吗?

However, what if I need to execute multiple commands during a single connection? Do I really need a new using block for each command?

我从Microsoft找到的示例没有对 SqlCommand 使用 using 块(甚至不调用 Dispose()).处置 SqlCommand 的最佳实践是什么?

The examples I found from Microsoft don't use a using block for SqlCommands (or even call Dispose()). What are best practices regarding disposing SqlCommand?

推荐答案

当然,最佳实践是处理它们.

Sure, best practice is to dispose them.

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可能不会显示它,因为它是如果是 SqlCommand ,则不是真正需要的.但是我认为对于Microsoft而言,不要在实现 IDdisosable 的每个对象上都使用这种模式是很不好的,因为人们对此并不习惯.

MSDN probably doesn't show it because it's not really needed in case of SqlCommand. But in my opinion it's bad from microsoft to not use this pattern on every object that implements IDdisosable because people aren't getting used to it.

这篇关于处置SqlCommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆