March 2008
Intermediate to advanced
982 pages
22h 43m
English
You want to access your data source using an ODBC provider from your .NET application.
Use the ODBC .NET data provider to access data exposed through an ODBC driver.
The solution creates an OdbcDataReader and uses it to output the FirstName and LastName columns from the first five rows in the Person.Contact table in the AdventureWorks sample database.
The C# code in Program.cs in the project ConnectOdbcDataSource is shown in Example 1-10.
Example 1-10. File: Program.cs for ConnectOdbcDataSource solution
using System;
using System.Data.Odbc;
namespace ConnectOdbcDataSource
{
class Program
{
static void Main(string[] args)
{
string odbcConnectString = "DRIVER={SQL Server};SERVER=(local);" +
"DATABASE=AdventureWorks;Trusted_Connection=yes;";
string sqlSelect = "SELECT TOP 5 Title, FirstName, LastName " +
"FROM Person.Contact";
// Create an ODBC Connection
using (OdbcConnection connection =
new OdbcConnection(odbcConnectString))
{
OdbcCommand command = new OdbcCommand(sqlSelect, connection);
// Execute the DataReader
connection.Open( );
OdbcDataReader reader = command.ExecuteReader( );
// Output the data from the DataReader to the console
while (reader.Read( ))
Console.WriteLine("{0} {1}", reader[0], reader[1]);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}The output is shown in Figure 1-9.

Figure 1-9. Output ...
Read now
Unlock full access