ADO.NET Connections

ADO.NET Connections are one of the simplest ways to connect to a database from a C# application. They rely on the use of a provider and a connection string that points to your database to perform queries against.

Common Data Provider Classes

Many of the following are classes that are commonly used to query databases and their related namespaces :

All of these are commonly used to access data through C# and will be commonly encountered throughout building data-centric applications. Many other classes that are not mentioned that implement the same FooConnection,FooCommand,FooDataReader classes can be expected to behave the same way.

Common Access Pattern for ADO.NET Connections

A common pattern that can be used when accessing your data through an ADO.NET connection might look as follows :

You can even program against a set of common interfaces and not have to worry about the provider specific classes. The core interfaces provided by ADO.NET are:

IDbConnection - for managing database connections

IDbCommand - for running SQL commands

IDbTransaction - for managing transactions

IDataReader - for reading data returned by a command

IDataAdapter - for channeling data to and from datasets

varconnectionString="{your-connection-string}";varproviderName="{System.Data.SqlClient}";//for Oracle use "Oracle.ManagedDataAccess.Client"
//most likely you will get the above two from ConnectionStringSettings object
varfactory=DbProviderFactories.GetFactory(providerName);using(varconnection=newfactory.CreateConnection()){connection.ConnectionString=connectionString;connection.Open();using(varcommand=newconnection.CreateCommand()){command.CommandText="{sql-query}";//this needs to be tailored for each database system
using(varreader=command.ExecuteReader()){while(reader.Read()){...}}}}