2010-05-17 46 views
1

关闭的SqlConnection我想知道,如果有什么问题在这个asp.net代码:如何在asp.net

如果我避免所谓的“MyDataReader.Close()”做的连接关闭吗? 我问这是因为我假设如果调用“MyConn.Close”,它会自动关闭相关的数据读取器......或者我错了吗?

由于

回答

3

最好的做法来执行这样的操作是如下:

using(SqlConnection connection = new SqlConnection(connStr)) { 
    connection.Open(); 

    SqlCommand command = new SqlCommand(connection, "SELECT..."); 
    SqlDataReader reader = command.ExecuteReader(); 
    // Fill your container objects with data 
} 

using语句:

定义范围,外面其中一个或多个物体将是处置。

所以你可以放心,您的connectioncommandreader变量将被关闭,并使用块退出当相应的配置。

+0

将读者和命令也被布置在这种情况下, ?我总是把所有这三个都用单独的陈述包装起来,这些陈述我总是觉得很烦人。如果是这样的话,可读性很好。 – MisterZimbu 2010-05-17 15:37:21

+1

直到垃圾回收器到达它时,读者将不会使用此代码关闭。使用嵌套的“使用”来处理读者。无需使用指定对象来执行此操作。 – Ray 2010-05-17 15:45:18

0

如果你既不关闭数据读取器也不关闭连接,垃圾回收器会为你做。另一方面,这可能会影响应用程序的性能。

+0

垃圾收集器不会隐式调用Dispose()。查看http://stackoverflow.com/questions/1691846/does-garbage-collector-call-dispose – 2010-05-17 15:43:56

0

我没有绝对的把握,但我总是使用try-catch-finally块为DB操作:

using (SqlConnection cnn = new SqlConnection(ConnectionString)) 
{ 
    using (SqlCommand cmmnd = new SqlCommand("SELECT Date();", cnn)) 
    { 
     try 
     { 
      cnn.Open(); 
      using (SqlDataReader rdr = cmmnd.ExecuteReader()) 
      { 
       if (rdr.Read()) { result = rdr[0].ToString(); } 
      } 
     } 
     catch (Exception ex) { LogException(ex); } 
     finally { cnn.Close(); } 
    } 
} 
+1

与日志的捕获是好的,因为使用调用关闭的配置最终不需要关闭。 – 2011-09-16 08:21:02