Visual Basic Code Snippet - Get XmlReader using open connection

Visual Basic Code Snippet - Get XmlReader using open connection

Visual Basic Code Snippet - Get XmlReader using open connection

(VB) Visual Basic code snippet connects to SQL server and executes SQL statement and return XmlReader. ExecuteXmlReader returns XmlReader using open database connection and SQL statement.

Bookmark:

Visual Basic Code Snippet - Get XmlReader using open connection

This .Net Visual Basic 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 Function ExecuteXmlReader(ByRef _SqlConnection As System.Data.SqlClient.SqlConnection, ByVal _SQL As String) As System.Xml.XmlReader
    ' Set temporary variable to create xml data reader
    Dim _XmlReader As System.Xml.XmlReader = Nothing

    ' lets run the given SQL statement and create XmlReader
    Try
        ' Pass the connection to a command object
        Dim _SqlCommand As New System.Data.SqlClient.SqlCommand(_SQL, _SqlConnection)

        ' get query results
        _XmlReader = _SqlCommand.ExecuteXmlReader()
    Catch _Exception As 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 Nothing
    End Try

    ' SQL successfully executed, lets return the XmlReader
    Return _XmlReader
End Function


VB Keywords Used:

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

Code Snippet Information:

  • Applies To: .Net, VB, Visual Basic, CLI, SQL, XmlReader, SQL Server, SQL Client, Connection String, Database Connection, SQL Data Reader
  • Programming Language : Visual Basic (VB)

External Resources:

Leave a comment