C++/CLI Code Snippet - Get XmlReader using open connection

C++/CLI Code Snippet - Get XmlReader using open connection

C++/CLI Code Snippet - Get XmlReader using open connection

C++/CLI 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++/CLI Code Snippet - Get XmlReader using open connection

This .Net C++/CLI 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.

System::Xml::XmlReader ^ExecuteXmlReader(System::Data::SqlClient::SqlConnection ^%_SqlConnection, System::String ^_SQL)
{
    // Set temporary variable to create xml data reader
    System::Xml::XmlReader ^_XmlReader = nullptr;

    // lets run the given SQL statement and create XmlReader
    try
    {
        // Pass the connection to a command object
        System::Data::SqlClient::SqlCommand ^_SqlCommand = gcnew 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 nullptr;
    }

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


C++/CLI 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++/CLI

External Resources:

Leave a comment