.net SqlCommand.ExecuteReader 是否关闭连接?

发布于 2024-07-07 19:12:33 字数 120 浏览 6 评论 0原文

在这句话中:

myCommand.ExecuteReader(CommandBehavior.CloseConnection)

如果出现异常,是否会关闭连接?

In this sentence:

myCommand.ExecuteReader(CommandBehavior.CloseConnection)

does it close connection in case of exception?

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

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

发布评论

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

评论(3

扬花落满肩 2024-07-14 19:12:33

执行“正常”查询的最安全方法是

using (var conn = new SqlConnection("..."))
{
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "...";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                // ...
            }
        }
    }
}

可以在此代码之外捕获异常。

The safest way to do a "normal" query is

using (var conn = new SqlConnection("..."))
{
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "...";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                // ...
            }
        }
    }
}

Exceptions can be caught outside this code.

几度春秋 2024-07-14 19:12:33

该命令有多种可能出错的方式。

最终,数据读取器的 Close 方法将关闭连接,前提是之前没有出现任何问题。

如果在构造实际的 DataReader 对象之前,在 ExecuteReader 或其任何调用的方法内部发生异常,则不会,连接不会关闭。

如果出现异常,我不相信它会关闭连接。

There are plenty of ways that the command can go wrong.

Ultimately it is the Close method of the data reader that will close the connection, provided nothing has gone wrong before.

If there is an exception that occurs inside ExecuteReader or any of its called methods, before the actual DataReader object is constructed, then no, the connection will not be closed.

In case of an exception, I wouldn't trust it to close the connection.

歌入人心 2024-07-14 19:12:33

这取决于异常发生在哪里!

如果你的 try catch 结构正确,那就没问题了。

例如:

SqlCommand myCommand = new SqlCommand();

try
{
   myCommand.dostuff();
}
catch(Exception ex)
{
  // display error message
}
finally
{
  myCommand.ExecuteReader(CommandBehavior.CloseConnection);
}

如果 myCommand.ExecuteReader(CommandBehavior.CloseConnection) 行失败(也许数据库已关闭?),则无法以编程方式关闭连接。

It depends where the exception occurs!

If you structure your try catch correctly, it will be fine.

For example:

SqlCommand myCommand = new SqlCommand();

try
{
   myCommand.dostuff();
}
catch(Exception ex)
{
  // display error message
}
finally
{
  myCommand.ExecuteReader(CommandBehavior.CloseConnection);
}

If the line: myCommand.ExecuteReader(CommandBehavior.CloseConnection) fails (perhaps the database has gone down?) then the connection cannot be closed programmatically.

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