Thursday, June 7, 2007

Provider independent connectivity code for dot net 2.0.

Provider independent connectivity code for dot net 2.0.
=======================================================


Make sure you use common namespace.

//Abstract ADO.NET Class
using System.Data.Common;

public DataSet getMyDS(string APINamespace, string Sql){
DbProviderFactory provider=DbProviderFactories.GetFactory(APINamespace);
DbConnection myConnection=provider.CreateConnection();


//you may dynamically pass connection string or pick it up from config file
myConnection.ConnectionString = "Data Source=(local);Initial Catalog=Northwind;User ID=sa;password=admin;";
myConnection.Open();

DbDataAdapter myAdapter = provider.CreateDataAdapter();
DbCommand myCommand = myConnection.CreateCommand();
myCommand.CommandText = Sql;
myAdapter.SelectCommand = myCommand;
DataSet myDataSet = new DataSet();
myAdapter.Fill(myDataSet);
myConnection.Close();
return myDataSet;
}

//You can call the above function as shown below

myDataGrid.DataSource = getMyDS("System.Data.SqlClient","select categoryname from categories").Tables[0].DefaultView;


// Prime provider classes of System.Data.Common
// DbConnection - to establish connection
// DbCommand - for quering to data source eg: update/select/delete sql statements
// DbDataReader - It is readonly/forwardonly access to datasource
// DbAdapter - It acts as a channel to connect to datasource ( i.e. dataset connects to
datasource)

No comments: