Monday, June 8, 2009

ADO.NET Database connections: SQLClient, OleDb, Odbc

ADO.NET
ADO.NET is a set of classes that expose data access services to the .NET programmer. ADO.NET provides a rich set of components for creating distributed, data-sharing applications. It is an integral part of the .NET Framework, providing access to relational data, XML, and application data. ADO.NET supports a variety of development needs, including the creation of front-end database clients and middle-tier business objects used by applications, tools, languages, or Internet browsers.

Code Samples of ADO.NET application that retrieves data from a database and returns it to the console.

SqlClient

using System;
using System.Data;
using System.Data.SqlClient;

class Sample
{
public static void Main()
{
SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");

SqlCommand catCMD = nwindConn.CreateCommand();
catCMD.CommandText = "SELECT CategoryID, CategoryName FROM Categories";

nwindConn.Open();

SqlDataReader myReader = catCMD.ExecuteReader();

while (myReader.Read())
{
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
}

myReader.Close();
nwindConn.Close();
}
}

OleDb


using System;
using System.Data;
using System.Data.OleDb;

class Sample
{
public static void Main()
{
OleDbConnection nwindConn = new OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");

OleDbCommand catCMD = nwindConn.CreateCommand();
catCMD.CommandText = "SELECT CategoryID, CategoryName FROM Categories";

nwindConn.Open();

OleDbDataReader myReader = catCMD.ExecuteReader();

while (myReader.Read())
{
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
}

myReader.Close();
nwindConn.Close();
}
}

Odbc

using System;
using System.Data;
using System.Data.Odbc;

class Sample
{
public static void Main()
{
OdbcConnection nwindConn = new OdbcConnection("Driver={SQL Server};Server=localhost;" +
"Trusted_Connection=yes;Database=northwind");

OdbcCommand catCMD = new OdbcCommand("SELECT CategoryID, CategoryName FROM Categories", nwindConn);

nwindConn.Open();

OdbcDataReader myReader = catCMD.ExecuteReader();

while (myReader.Read())
{
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
}

myReader.Close();
nwindConn.Close();
}
}

No comments: