当读取时执行exmlreader和CloseConnection.这叫接近

本文关键字:CloseConnection 接近 exmlreader 读取 执行 | 更新日期: 2023-09-27 18:03:50

我有一个静态数据访问类与静态方法:MyExecuteReader(返回sqldatareader)和MyExecuteXmlReader(返回XmlReader)。

现在使用ExecuteReader方法,我可以执行SqlCommand.ExecuteReader(CommandBehavior.CloseConnection),这将在我关闭阅读器时关闭连接。

SqlCommand.ExecuteXmlReader()没有类似的方法

那么,在这种情况下,确保相应连接关闭的最佳方法是什么?

注意:

我的查询返回XML,即使用FOR XML AUTO。这就是我使用XmlReader的原因。返回的字段被认为是SqlString。我可以使用SqlDataReader。GetSqlString方法,但我不确定这是一个好方法或不是。

更新:

我可以将XML读入字符串并从DAL返回字符串而不是XmlReader。

我知道using语句,不知怎么的,这个选项被排除了,我相信是由于一些异常处理问题。

当读取时执行exmlreader和CloseConnection.这叫接近

我有一个静态的DataAccess类的静态方法:myexecuterreader(返回sqldatareader)和MyExecuteXmlReader(返回sqldatareader)XmlReader)。

这太可怕了。通过阅读这句话,我必须说,为这些事情使用静态方法似乎是错误的。我只会依赖于ADO。. NET连接池并将连接包装到using语句中。处理掉它们并不会在物理上切断联系。它只是将它返回到连接池以便被重用。

但是,因为你走这种方式(使用静态连接和东西,使你的代码完全不适合单元测试),我所能建议的是,至少将对这个XmlReader的调用包装到using语句中,以至少确保你释放了底层句柄,否则你将会严重泄漏,这在多线程应用程序中可能会有灾难性的后果。

我最终修改了MyExecuteXmlReader (返回XmlReader)在我的DAL到MyExecuteXmlReader (返回字符串)。

所以现在我从XmlReader读取到一个字符串,并返回这个字符串,而不是XmlReader,这解决了关闭阅读器和连接之外的DAL的问题。

DataReader每次读取一行,使连接保持繁忙。

XmlReader一次性读取结果,并且不会使连接保持繁忙状态。所以没有必要关闭它

使用语句实现。例如:

using (SqlConnection conn = new SqlConnection(connString))
{
  using(SqlCommand cmd = conn.CreateCommand())
  {
     cmd.CommandText = "SELECT ID, Name FROM Customers";
      conn.Open();
      using (SqlDataReader dr = cmd.ExecuteReader())
      {
          while (dr.Read())
          {
              // do your thing
          }
      }
  }
}

EDIT: Put missing using around SqlCommand

这是使用更多

的方法
[Visual Basic] 
Public Sub ReadMyData(myConnString As String)
    Dim mySelectQuery As String = "SELECT OrderID, CustomerID FROM Orders"
    Dim myConnection As New SqlConnection(myConnString)
    Dim myCommand As New SqlCommand(mySelectQuery, myConnection)
    myConnection.Open()
    Dim myReader As SqlDataReader
    myReader = myCommand.ExecuteReader()
    ' Always call Read before accessing data.
    While myReader.Read()
        Console.WriteLine((myReader.GetInt32(0) & ", " & myReader.GetString(1)))
    End While
    ' always call Close when done reading.
    myReader.Close()
    ' Close the connection when done with it.
    myConnection.Close()
End Sub 'ReadMyData
[C#] 
public void ReadMyData(string myConnString) {
    string mySelectQuery = "SELECT OrderID, CustomerID FROM Orders";
    SqlConnection myConnection = new SqlConnection(myConnString);
    SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection);
    myConnection.Open();
    SqlDataReader myReader;
    myReader = myCommand.ExecuteReader();
    // Always call Read before accessing data.
    while (myReader.Read()) {
       Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(1));
    }
    // always call Close when done reading.
    myReader.Close();
    // Close the connection when done with it.
    myConnection.Close();
 }