Library code snippets

Database Independent ADO.NET 2.0

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

  1. 01 Jan 1999 at 00:00

    This thread is for discussions of Database Independent ADO.NET 2.0.

Leave a comment

Sign in or Join us (it's free).

Xavier Larrea

Related podcasts

Events coming up

  • Mar 15

    DevWeek 2010

    London, United Kingdom

    DevWeek is Europe’s leading independent conference for software developers, database professionals and IT architects, and features expert speakers on a wide range of topics, including .NET 4.0, Silverlight 3, WCF 4, Visual Studio 2010, REST, Windows Workflow 4, Thread Synchronization, ASP.NET 4.0, SQL Server 2008 R2, LINQ, Unit Testing, CLR & C# 4.0, .NET Patterns, WPF 4, F#, Windows Azure, ADO.NET, Entity Framework, Debugging, T-SQL Tips & Tricks, and more.

We'd love to hear what you think! Submit ideas or give us feedback