您的位置:首页 > 其它

Enterprise Library 4.1数据访问应用程序块快速入门【7】在XML中进行多行检索

2010-01-13 12:28 537 查看
本演练演示如何从SQL Server数据库中检索XML数据。
1、配置数据库。必要的步骤,请参阅数据访问快速入门。
2、创建Database(当你不使用统一的集成方法)。下面的代码使用工厂创建一个默认的配置的SqlDatabase对象。

SqlDatabase dbSQL = DatabaseFactory.CreateDatabase() as SqlDatabase;


Dim dbSQL As SqlDatabase = DirectCast(DatabaseFactory.CreateDatabase(), SqlDatabase)


3、使用下面代码创建一个命令。它使用SQL字符串创建了一个DbCommand。

string sqlCommand = "Select ProductID, ProductName, CategoryID, UnitPrice, " 
                  + "LastUpdate From Products FOR XML AUTO";
DbCommand dbCommand = dbSQL.GetSqlStringCommand(sqlCommand);


Dim sqlCommand As String = "Select ProductID, ProductName, CategoryID, " _
                         & " UnitPrice, LastUpdate From Products FOR XML AUTO"

Dim dbCommand As DbCommand = dbSQL.GetSqlStringCommand(sqlCommand)


4、添加下面的代码调用ExecuteXmlReader并处理结果

XmlReader productsReader = null;
StringBuilder productList = new StringBuilder();

try

{
  productsReader = dbSQL.ExecuteXmlReader(dbCommand);

  while (!productsReader.EOF)
  {
    if (productsReader.IsStartElement()) 
    {
      productList.Append(productsReader.ReadOuterXml());
      productList.Append(Environment.NewLine);
    }
  }   
}


Dim productsReader As XmlReader = Nothing
Dim productList As StringBuilder = New StringBuilder()

Try

  productsReader = dbSQL.ExecuteXmlReader(dbCommand)

  While (Not productsReader.EOF)
    If (productsReader.IsStartElement()) Then
      productList.Append(productsReader.ReadOuterXml())
      productList.Append(Environment.NewLine)
    End If
  End While


5、使用下面的代码关闭XmlReader和Connection。

finally
{
  // Close the Reader.
  if (productsReader != null)
  {
    productsReader.Close();
  }

  // Explicitly close the connection. The connection is not closed
  // when the XmlReader is closed.
  if (dbComman.Connection != null)
  {
    dbCommand.Connection.Close();
  }       
}


Finally
  ' Close the Reader.
  If (Not productsReader Is Nothing) Then
    productsReader.Close()
  End If

  ' Explicitly close the connection. The connection is not closed
  ' when the XmlReader is closed.
  If (Not dbCommand.Connection Is Nothing) Then
    dbCommand.Connection.Close()
  End If
End Try


文章由唐勇(http://www.tangyong.net/)翻译自微软Enterprise Library系列英文文档,翻译得辛苦,转载请保留,谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐