Share via


SqlCommand.ExecuteXmlReader 方法

定义

CommandText 发送到 Connection,并生成一个 XmlReader 对象。

public:
 System::Xml::XmlReader ^ ExecuteXmlReader();
public System.Xml.XmlReader ExecuteXmlReader ();
member this.ExecuteXmlReader : unit -> System.Xml.XmlReader
Public Function ExecuteXmlReader () As XmlReader

返回

一个 XmlReader 对象。

例外

SqlDbType当 设置为 StreamValue,使用 BinaryVarBinary 以外的 。 有关流式处理的详细信息,请参阅 SqlClient 流支持

- 或 -

SqlDbType设置为 时ValueTextReader ,使用了 CharNCharNVarCharVarCharXml 以外的其他项。

-或-

SqlDbType设置为 时ValueXmlReader ,使用了 Xml 以外的 。

对锁定的行执行命令时出现异常。 当使用 Microsoft .NET Framework 1.0 版时不生成此异常。

- 或 -

流式处理操作期间发生了超时。 有关流式处理的详细信息,请参阅 SqlClient 流支持

流式处理操作期间关闭或删除了 SqlConnection。 有关流式处理的详细信息,请参阅 SqlClient 流支持

在流式处理操作期间, XmlReaderTextReader 对象中Stream发生错误。 有关流式处理的详细信息,请参阅 SqlClient 流支持

StreamXmlReader流式处理操作期间, 或 TextReader 对象已关闭。 有关流式处理的详细信息,请参阅 SqlClient 流支持

示例

以下示例创建 , SqlCommand 然后使用 执行它 ExecuteXmlReader。 该示例传递了一个字符串,该字符串是 Transact-SQL FOR XML SELECT 语句,以及用于连接到数据源的字符串。

using System;
using System.Data;
using Microsoft.Data.SqlClient;

private static void CreateXMLReader(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        connection.Open();
        SqlCommand command = new SqlCommand(queryString, connection);
        System.Xml.XmlReader reader = command.ExecuteXmlReader();
    }
}

注解

此方法返回的 XmlReader 不支持异步操作。 属性 CommandText 通常指定具有有效 FOR XML 子句的 Transact-SQL 语句。 但是, CommandText 也可以指定一个语句,该语句返回 ntextnvarchar 包含有效 XML 的数据,或者指定使用 xml 数据类型定义的列的内容。

典型的 ExecuteXmlReader 查询的格式可以设置为以下 Microsoft Visual C# 示例中的格式:

SqlCommand command = new SqlCommand("SELECT * FROM dbo.Customers FOR XML AUTO, XMLDATA", SqlConn);

此方法还可用于检索包含 XML 数据的单行、单列结果集。 在这种情况下,如果返回了多行,该方法 ExecuteXmlReader 会将 XmlReader 附加到第一行的值,并放弃结果集的其余部分。

MARS) 功能 (多个活动结果集允许使用同一连接执行多个操作。

如果使用 ExecuteReaderBeginExecuteReader 访问 XML 数据,SQL Server将返回长度超过 2,033 个字符的任何 XML 结果,每行 2,033 个字符。 若要避免此行为,请使用 ExecuteXmlReaderBeginExecuteXmlReader 读取 FOR XML 查询。

适用于