简体   繁体   English

“connection.Close()”是关闭SQL连接的最佳或最安全的方法吗?

[英]Is “connection.Close()” the best or safest way to close an SQL connection?

I've been using 我一直在用

connection.Close();

But this is my first project in .NET and I'm not sure if I'm closing it correctly. 但这是我在.NET中的第一个项目,我不确定我是否正确关闭它。

I don't want my website to instantly die after putting it out on real hosting. 我不希望我的网站在真正托管之后立即死亡。

Usually I do it this way: 通常我会这样做:

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());

    SqlCommand cmd = new SqlCommand();

    cmd.Connection = conn;

    // <some code>

    conn.Open();
    / <some code>
    conn.Close();

You should place the connection in a using statement; 您应该将连接放在using语句中;

using(var connection = new SqlConnection)
{
  connection.Open();
  ...other code using it here.
}

The using statement ensures that the SqlConnection is disposed when you are done with it. using语句确保在完成SqlConnection后处理它。 In your scenario (depending on where you put the close method), if an exception is closed, it will never reach the Close() method and the connection will stay open. 在您的方案中(取决于您放置close方法的位置),如果异常关闭,它将永远不会到达Close()方法,并且连接将保持打开状态。

Even better is that since you are building a website. 更好的是,因为你正在建立一个网站。 There should be a method on the Request object (which should be available) called RegisterForDispose. Request对象(应该可用)上应该有一个名为RegisterForDispose的方法。 This will automatically Dispose of the connection (which closes it) when the request ends. 这将在请求结束时自动处理连接(关闭它)。 You can use it like this: 你可以像这样使用它:

var connection = new SqlConnection();
Request.RegisterForDispose(connection);

Both accomplish the same thing in the end, but the second allows for more flexibility. 两者最终完成相同的事情,但第二个允许更多的灵活性。

Do what Kevin said and put your .Open() call inside the using block: 做Kevin所说的并将你的.Open()调用放在using块中:

using(var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
    var cmd = new SqlCommand("my sql command here", conn);

    conn.Open();

    cmd.(whatever method you are using)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM