Creating a Simple ADO.NET Application


Now, let's use all of the previous steps and write a console-based application to read data and display it on the console. In this application, you'll read data from the Northwind database's Customers table and display it on the console.

In this example, you'll use VS .NET to create a console application by selecting Visual Basic Projects and then choosing the Console Application template from the Templates listing. Name your project FirstAdoNetApp1.

After creating the project, add the Listing 1-1 source code to the project. As you can see from this listing, first you import the required namespace. Second, you create a connection and create an OleDbConnection object by passing the connection string as only one argument. Next, you construct a SELECT statement and create an OleDbCommand object by passing the SQL statement and connection object. Then you open the connection by calling the OleDbConnection.Open method. Once a connection is opened, you can execute SQL statement by simply calling the ExecuteXXX methods of the DataReader. As you can see, the code calls the ExecuteReader method, which returns data in an OleDataReader object. Then you read data from the DataReader and display it on the console. The last step is to close the DataReader and the connection. You do this by calling the Close methods of OleDbDataReader and OleDbConnection objects.

Listing 1-1: Your ADO.NET Application

start example
 Imports System Imports System.Data Imports System.Data.OleDb Imports System.Data.Common Module Module1   Sub Main()     Dim connectionString As String     Dim sql As String     'Create connection and command objects ConnectionString = "Integrated Security=SSPI; Initial Catalog=Northwind; " & _ "Data Source=localhost;"     Dim conn As OleDbConnection = New OleDbConnection(connectionString)     sql = "SELECT CustomerID, ContactName, ContactTitle FROM Customers"     Dim cmd As OleDbCommand = New OleDbCommand(sql, conn)     'Open connection     conn.Open()     'Call ExecuteReader     Dim reader As OleDbDataReader = cmd.ExecuteReader()     Console.WriteLine("Contact Name, Contact Title")     Console.WriteLine("=======================")     'Read data until reader has data     While reader.Read()       Console.Write(reader.GetString(0).ToString() + " ,")       Console.Write(reader.GetString(1).ToString() + " ,")       Console.WriteLine("")     End While     ' Close reader and connection     reader.Close()     conn.Close()   End Sub End Module 
end example

Now compile and run the project. You should see data on the console (see Figure 1-15).

click to expand
Figure 1-15: Displaying data on the console using DataReader




Applied ADO. NET(c) Building Data-Driven Solutions
Applied ADO.NET: Building Data-Driven Solutions
ISBN: 1590590732
EAN: 2147483647
Year: 2006
Pages: 214

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net