Configuring an ODBC Connection String

Configuring an ODBC Connection String

Open Database Connectivity (ODBC) is one of the older technologies the .NET Framework supports, primarily because you still need the .NET Framework to connect to older database products that have ODBC drivers.

 

Following example shows how to access  data source using an ODBC provider :



using System;
using System.Data.Odbc;

namespace ODBCConnectionString
{
class Program
{
static void Main(string[] args)
{
string odbcConnectString = "DRIVER={SQL Server};SERVER=(local);DATABASE=AdventureWorks;Trusted_Connection=yes;";

string sqlSelect = "SELECT TOP 4 ProductID, Name, ProductNumber FROM Production.Product";

// 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
Console.WriteLine("ProductID\tProductName\t\tProductNumber\n");
while (reader.Read())
Console.WriteLine("{0}\t\t{1}\t\t{2}", reader[0], reader[1], reader[2]);
}

Console.WriteLine("\nPress any key to continue.");
Console.ReadLine();

}
}
}


Output :

ODBC.bmp

The following ODBC providers are guaranteed to be compatible with the ODBC.NET data provider:

  • SQL Server
  • Microsoft ODBC for Oracle
  • Microsoft Access Driver (*.mdb)
Next Recommended Reading Configuring an OLEDB Connection String