ADO.NET 2 has new clases that makes it quite easy to write
data-programs independent of the database engine. Its all done through
the System.Data.Common
namespace and mainly with the DbProviderfactory
class.
Simply put, we need first an instance of the factory with the provider name, For this example, we will use System.Data.SqlClient.
DbProviderFactory provider = DbProviderFactories.GetFactory("System.Data.SqlClient");
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
Now you have you connection object ready to be used. We can now use it to call a stored procedure to the server:
DbCommand dbcmd = conn.CreateCommand();
dbcmd.Connection = conn;
dbcmd.CommandText = "GetPageByID";
dbcmd.CommandType = CommandType.StoredProcedure;
// If your SP requires input parameters
DbParameter oParam1 = dbcmd.CreateParameter();
oParam1.ParameterName = "@PageID";
oParam1.DbType = DbType.Int32;
oParam1.Value = ID;
dbcmd.Parameters.Add(oParam1);
DbDataReader dr = dbcmd.ExecuteReader();
And that's it. You are ready to consume the DataReader as usual. Remember you can enumerate the avaliable providers using the DbProviderFactories.GetFactoryClasses()
method. Happy Coding!
Comments