C# Code Snippet - Get XmlReader using open connection

C# Code Snippet - Get XmlReader using open connection

C# Code Snippet - Get XmlReader using open connection

(C-Sharp) C# code snippet connects to SQL server and executes SQL statement and return XmlReader. ExecuteXmlReader returns XmlReader using open database connection and SQL statement.

Bookmark:

C# Code Snippet - Get XmlReader using open connection

This .Net C# code snippet connect connects to SQL server and executes SQL statement and return XmlReader. To use this function simply provide open database connection and SQL statement. This function uses SqlClient name space to get data using XmlReader. Modify the exception handling section to as your project requirements.

public System.Xml.XmlReader ExecuteXmlReader(
                ref System.Data.SqlClient.SqlConnection _SqlConnection,
                string _SQL)
{
    // Set temporary variable to create xml data reader
    System.Xml.XmlReader _XmlReader = null;

    // lets run the given SQL statement and create XmlReader
    try
    {
        // Pass the connection to a command object
        System.Data.SqlClient.SqlCommand _SqlCommand =
                new System.Data.SqlClient.SqlCommand(_SQL, _SqlConnection);

        // get query results
        _XmlReader = _SqlCommand.ExecuteXmlReader();
    }
    catch (Exception _Exception)
    {
        // Error occurred while trying to execute reader
        // send error message to console (change below line to customize error handling)
        Console.WriteLine(_Exception.Message);

        // failed SQL execution, lets return null
        return null;
    }

    // SQL successfully executed, lets return the XmlReader
    return _XmlReader;
}


C# Keywords Used:

  • XmlReader
  • ExecuteXmlReader
  • SqlConnection
  • ConnectionString
  • SqlCommand
  • Exception

Code Snippet Information:

  • Applies To: .Net, C#, CLI, SQL, XmlReader, SQL Server, SQL Client, Connection String, Database Connection, SQL Data Reader
  • Programming Language : C# (C-Sharp)

External Resources:

Leave a comment