ADO.NET Sql and ODBC Command Objects in VB.NET

In this article I will explain Creating Sql and ODBC Command Objects in ADO.NET.
  • 3088

Similar to the OldDbCommand object, you create Sql and ODBC Command objects by using SqlCommand and OdbcCommand classes. You can pass the same arguments as discussed previously. The only difference is the connection string. For Example, listing 5-31 uses SqlCommand and SqlConnection to connect to SQL server database. As you can see from listing 5-31, the only changes are the class prefixes and the connection string. Similarly, you can use the OdbcCommand object.

Listing 5-31. Using SqlCommand to access a SQL Server database


Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Data.SqlClient

Namespace ConsoleApplication1
    Class Program
        Private Shared Sub Main(ByVal args As String())

            ' Connection and SQL strings 
            Dim SQL As String = "SELECT * FROM Orders"

            ' create a connection object 
            Dim ConnectionString As String = "Integrated security =SSPI;" & "Initial Catalog = Northwind;" & "Data Source = MAIN-SERVER; "
            Dim conn As New SqlConnection(ConnectionString)

            ' create command object 
            Dim cmd As New SqlCommand(SQL, conn)

            ' open connection 
            conn.Open()

            ' call command's ExcuteReader 
            Dim reader As SqlDataReader = cmd.ExecuteReader()

            Try
                While reader.Read()
                    Console.Write("OrderID:" & reader.GetInt32(0).ToString())
                    Console.Write(" ,")
                    Console.WriteLine("Customer : " & reader.GetString(1).ToString())
                End While
            Finally

                ' close reader and connection 
                reader.Close()
                conn.Close()
            End Try
        End Sub
    End Class
End Namespace

Conclusion

Hope this article would have helped you in understanding 
Creating Sql and ODBC Command Objects in ADO.NET. See my other articles on the website on ADO.NET.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.