IDbHelper

Many times I put together some quick and dirty solutions where I need to hit a database for a few queries, simple stuff where NHibernate and/or ActiveRecord are overkill.  I came up with a utility that encapsulated many of the common ADO stuff I was doing.  I did some refactoring and pulled the methods out into an interface, IDbHelper.  Yesterday I took some time to document all of the methods on the interface.  I also refactored the interface to use the interfaces in ADO rather than the sql server specific classes I was using(cuz pretty much everything I do is done in sql server).  Here's the interface:

This is not ground breaking in any way, shape, or form.  But it is simple which is why I use it often for quick and dirty stuff.  Essentially it aleviates having to write a bunch of the same code I commonly write.

One thing I find myself doing a lot of, are queries that involve getting the values from a single column and converting them to an array.  This usually involves iterating over a resultset or using an IDataReader and spinning through that.  Anyway, that's where ExecuteArray comes in.  It let's me do this:

string[] firstNames = _dbhelper.ExecuteArray("select first_name from customer");

One thing I see at work from other devs is when a single value needs to be retrieved from the database, either a SqlDataReader is used and the first value returned is plucked out; or better yet, an entire DataTable is filled, and the value is manually pulled out of the first column of the first row. Using the IDbHelper interface this is achieved like this:

DateTime birthday = 
  _dbhelper.ExecuteScalar(@"
    select birthday from customer where first_name = 'Chris'
");

Filling a DataTable should be a one liner, I don't want to know about a connection or data adapter, just get my DataTable, like this:

DataTable data = _dbhelper.ExecuteDataTable("select * from customer");

Anyway, again, it's not meant to be anything than a utility class when the database interaction in an application is minimal, and I just need to execute some one-off type queries.

Click here to download the solution.

 

 
Author: , 0000-00-00