当命令被处理并且连接是直接在命令上定义时,连接是否会关闭?

发布于 2024-07-11 21:20:28 字数 452 浏览 4 评论 0原文

我知道有很多例子,其中定义了 SqlConnection,然后定义了 SqlCommand,两者都在使用块中:

using (var conn = new SqlConnection(connString)) {
      using (var cmd = new SqlCommand()) {
        cmd.Connection = conn;
        //open the connection
      }
}

我的问题:如果我直接在 SqlCommand 上定义连接,则在处理命令时连接会关闭吗?

using (var cmd = new SqlCommand()) {
      cmd.Connection = new SqlConnection(connString);
      //open the connection
}

I know that a lot of examples exist where a SqlConnection is defined and then a SqlCommand is defined, both in Using blocks:

using (var conn = new SqlConnection(connString)) {
      using (var cmd = new SqlCommand()) {
        cmd.Connection = conn;
        //open the connection
      }
}

My question: If I define the connection directly on the SqlCommand, does the connection close when the command is disposed?

using (var cmd = new SqlCommand()) {
      cmd.Connection = new SqlConnection(connString);
      //open the connection
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

走过海棠暮 2024-07-18 21:20:28

不,SqlCommand 从不尝试关闭/处置连接。

No, SqlCommand never attempts to close/dispose of the connection.

吝吻 2024-07-18 21:20:28

不,除非您显式处置连接对象,否则不会对其进行处置。 但我的建议是尽可能使用使用块

No, the connection object will not be disposed until you dispose it explicitly. But my recommendation is to use using blocks whenever you can.

樱娆 2024-07-18 21:20:28

它不会关闭连接,您需要自己关闭它或将其放在自己的 using 语句中。

另外,这里还有一个技巧,可以让您的 using 块更具可读性:

using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand())
{
    cmd.Connection = conn;
}

It does not close the connection, you need to either close it yourself or put it in its own using statment.

Also here is a tip to make your using blocks a bit more readable:

using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand())
{
    cmd.Connection = conn;
}
独闯女儿国 2024-07-18 21:20:28

@米洛特

但我的建议是尽可能使用 using 块。

使用“使用块”很好,但在处理非 IDisposable 对象时毫无用处,因此如果您在任何地方使用“使用块”,这可能会令人困惑。

请小心,因为如果您的对象未实现 IDisposable,则它们可能不会被释放。

希望这可以帮助。

@milot

But my recommendation is to use using blocks whenever you can.

Using Using Blocks is nice but useless when working with non IDisposable Objects and so this can be confusing if you use Using Blocks anywhere.

Be careful since your objects might not being Disposed if they don't implements IDisposable.

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文