ExecuteXMLReader 메서드를 사용하여 SQL 쿼리 실행

적용 대상: SQL Server Azure SQL 데이터베이스

ExecuteToStream 메서드를 사용하는 대신 SqlXmlCommand 개체의 ExecuteXmlReader 메서드를 사용하여 명령을 실행할 수 있습니다. 이 메서드는 결과의 추가 처리에 사용할 수 있는 XmlReader 개체를 반환합니다(이 예제에서는 요소 또는 특성 이름 및 값을 인쇄하는 경우).

참고

코드에서 연결 문자열에 Microsoft SQL Server instance 이름을 제공해야 합니다.

using System;  
using Microsoft.Data.SqlXml;  
using System.IO;  
using System.Xml;  
   class Test  
   {  
      static string ConnString = "Provider=SQLOLEDB;Server=(local);database=AdventureWorks2022;Integrated Security=SSPI";  
      public static int testParams()  
      {  
         SqlXmlParameter p;  
         XmlReader Reader;  
         XmlTextWriter tw;  
         SqlXmlCommand cmd = new SqlXmlCommand(ConnString);  
         cmd.CommandText = "select FirstName, LastName from Person.Person where LastName = ? For XML Auto";  
         p = cmd.CreateParameter();  
         p.Value = "Achong";  
         Reader = cmd.ExecuteXmlReader();  
            tw = new XmlTextWriter(Console.Out);  
         Reader.MoveToContent();  
         tw.WriteNode(Reader, false);  
         tw.Flush();  
         tw.Close();  
         Reader.Close();  
  
         return 0;  
      }  
  
      static int Main(string[] args)  
      {  
         testParams();  
         return 0;  
      }  
   }  

애플리케이션을 테스트하려면

  1. 컴퓨터에 Microsoft .NET Framework 설치되어 있는지 확인합니다.

  2. 이 항목에 나오는 C# 코드(DocSample.cs)를 폴더에 저장합니다.

  3. 코드를 컴파일합니다. 다음을 사용하여 명령 프롬프트에서 코드를 컴파일합니다.

    csc /reference:Microsoft.Data.SqlXML.dll DocSample.cs  
    

    이렇게 하면 실행 파일(DocSample.exe)이 만들어집니다.

  4. 명령 프롬프트에서 DocSample.exe를 실행합니다.