Simple C# Wrapper Class for SQL Server

Whilst database technology and the way we create and interact with database has changed significantly with the use of Object-Relational Mapping, however prefer to create the Tables and Queries myself within the database as it is my opinion that this offers greater flexibility and easier maintainability.

Upon finding myself writing the same boilerplate code over and over to interact with a database (A problem that ORMS effectively eliminate), I decided to create my own C# Wrapper Class for SQL Server. In doing so, I have significantly reduced the amount of code needed to run a query – simple or complex!

It is worth noting that this wrapper class is being actively developed, with new features added as and when I find that I need them.

The Class

Since the class is several hundred lines long (I like human readable code) I’ve hosted it externally: View Class on PasteBin


Once included in your project, usage for this class is fairly simple. An example might be:

    //Usage example for the database wrapper class     
     private bool validateOrder( )
            //Create a new Database object
            Database database = new Database();
            //Add optional parameters to the query
                new SqlParameter() { ParameterName = "OrderID", Value = txtOrderID.Text.Trim(), SqlDbType = SqlDbType.NvarChar }
                new SqlParameter() { ParameterName = "EmailAddress", Value = txtEmail.Text.Trim(), SqlDbType = SqlDbType.NvarChar }
                new SqlParameter() { ParameterName = "PostCode", Value = txtPostCode.Text.Trim(), SqlDbType = SqlDbType.NvarChar }
            //Execute the query - give it the name of the stored procedure and set "hasParams" flag to true (or false if none).
            database.runSelect( "RETURNS_GET_ValidateOrder", true);
            //The results table is stored within the object and can be accessed as follows:
            if ( database.resultsTable.Rows.Count == 1 )
                return true;
                return false;

Known Caveats

  • This class doesn’t deal with datasets, only datatables.
  • Could have better Error handling – EG: Store SQLExceptions within the object

Please do let me know what you think, and what features you would like to see added.

Use of this code is entirely Open-Source. You are free to use it however you want; Commercially or Non-Commercially, but note: I provide absolutely no warranties for it’s use. This material has been posted as educational material, that may not be suitable for a production environment.