Click here to Skip to main content
Click here to Skip to main content

A Helpful Database Library

By , 6 Dec 2006
 

Introduction

There is a question that all programmers ask themselves, "What is that connection string format?" Another one that I ask myself still is, "Is it OLE, ODBC, or SQL?" Well, I know there are many different ways to interact and connect with databases. I am going to show you a way that I like to write code for database programming. Please, forgive me for any mistakes; this is my first article, and I am not a great technical writer.

How do we work with databases

First, let's ask ourselves a few questions:

  1. Does my program need to connect to a database?
  2. What kind of database will it be, i.e., MS SQL, MS Access, MySQL?
  3. What action will I be making on the database, i.e., SELECT, INSERT, CREATE?

For this example, let's say:

  1. Yes, we need a database,
  2. The database will be MS Access, and
  3. We need to return (SELECT) records from the database.

Now that we know what it is we will be doing, let's get to the basics. To programmatically run a SQL statement against a database, we need a couple of things at the bare minimum.

  1. A Connection class
  2. A Command class

For an Access database, it would be something like this:

OleDBConnection _OleConn = new OleDbConnection(ConnectionString);
OleDbCommand _OleCmd = new OleCommand(SQLstring, _OleConn;

But we still need to run the SQL against the database, so:

_OleConn.Open();
//or
_OleCmd.Connection.Open();
OleCmd.ExecuteNonQuery();
_OleConn.Close();
//or
_OleCmd.Connection.Open();

Pretty easy, well at least after you have done it a few times. I know that starting out as a newbie, that stuff can get confusing. But with places like CodeProject and Google, you can figure out almost any problem you have. Now, let's try to get our hands good and dirty.

I do not like loops and hoops

One of the biggest problems that a young programmer can face is OOP. What I mean is, we can be tempted to put too much code into a method (or a function) either to be able to see it in one place or just not knowing any better. Breaking up your code into logical sections helps a lot. Let's take a database call for instance. If you know that you will be making repeated calls to a database from multiple methods, do not put the code in each method. Create a method that holds the database code, and call it every time. I know I am talking about basics here, but hang in there. So here is what I do: I have a 'DB' class that has a static method 'RunSqlCommand', and it takes an argument 'MySqlData', which is a different class that hold values like connection string, provider (I'll explain), and the SQL command to be run.

public static class MyDatabase
{
    public static void RunSqlCommands(MySqlData _MySQLData)
    {
        if (_MySQLData.MyDatabaseProvider == DatabaseProvider.MicrosoftJet)
        {
            OleDbConnection MyOleConn = 
              new OleDbConnection(_MySQLData.MyConnectionString);
            OleDbCommand MyOleComm = 
              new OleDbCommand(_MySQLData.MySQLString, MyOleConn);
            MyOleComm.Connection.Open();
            MyOleComm.ExecuteNonQuery();
            MyOleComm.Connection.Close();
        }
        else
        {
            SqlConnection MySqlConn = 
              new SqlConnection(_MySQLData.MyConnectionString);
            SqlCommand MySqlComm = 
              new SqlCommand(_MySQLData.MySQLString, MySqlConn);
            MySqlComm.Connection.Open();
            MySqlComm.ExecuteNonQuery();
            MySqlComm.Connection.Close();
        }
    }
}

You do not need to make the class static, but it does help if you do so. This way, all you have to do is call MyDatabase.RunSqlCommands(_MySQLData);. It just make things easier.

Connection string

Getting the connection string for a database is pretty easy (Google) once you have the right format. You can store it in your program in many different ways. One thing I do stress on is do not hard code it into your program unless you know that the database will never move or have a name change, or if your program will never work with a different database. Even then, I wouldn't hard code it in. Okay, so let's say that our program will create tables in and work with those tables. If designed right, your program can work with SQL Server, Access, MySQL, and Oracle. So, you will need a way to generate a connection string for each one of them. Well, I think I have a real good way to do just that.

Data Link Properties Dialog Box:

You can implement this into your program with ease, and this is very useful. Here is how. Add a reference to:

  • Microsoft ActiveX Data Objects 2.8 Library
  • Microsoft OLE DB Service Component 1.0 Type Library

Then add the following using statements:

using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using MSDASC; // add this
using ADODB;  // add this

The code to implement it:

public static void GenerateConnectionString(ref MySqlData _MySqlData)
{
    DataLinksClass MyDataLink = new DataLinksClass();
    Connection MyADOConn = (Connection)MyDataLink.PromptNew();
    if (MyADOConn.Provider == "Microsoft.Jet.OLEDB.4.0")
    {
        _MySqlData.MyDatabaseProvider = DatabaseProvider.MicrosoftJet;
        _MySqlData.MyConnectionString = MyADOConn.ConnectionString;
    }
    else
    {
        _MySqlData.MyDatabaseProvider = DatabaseProvider.MicrosoftSQL;
        _MySqlData.MyConnectionString  = MyADOConn.ConnectionString;
        _MySqlData.MyConnectionString  = _MySqlData.MyConnectionString.Substring(
            (_MySqlData.MyConnectionString.IndexOf(";") + 1),
                (_MySqlData.MyConnectionString.Length - (
                    (_MySqlData.MyConnectionString.IndexOf(";") + 1))));
    }
}

Again, I use a static method because I don’t need to implement it everywhere. Also, I passed a ‘ref’ of _MySqlData to it and the method handle assigning values to many connection strings and providers.

Warning

I have found that when using these methods in a multithreaded program, I get errors when when one thread tries to execute a method while another is in the process of executing the same method. I have tried Monitor.Lock and just Lock. But the best method that I found is to change the method to non-static and create an instance of the class. Now I am sure someone probably just called me stupid for saying that, but I also know someone just said thanks for showing me that.

MyDatabaseLibrary

I have something I use called MyDatabaseLibrary. It is a DLL file that contains a lot of database code. The library is very simple (simple=good), you can see it here:

With this library, I can use:

  • MyDatabse class
    1. Run SQL, i.e., INSERT, CREATE against a database with ‘RunSqlCommands
    2. Get the tables from a database with ‘GetDataBaseSchema
    3. Return a record, or sets of records, or a whole table with ‘GetDataTable
    4. Generate a connection string with ‘GenerateConnectionString
  • MySqlData class stores:
    1. Connection string
    2. Database provider
    3. SQL command to execute

The DatabaseProvider enum stores a list of database providers the library uses.

Using MyDatabaseLibrary

This is the good part. To use this library, here are the steps you need to follow:

  1. Create a new instance of MySqlData, say, _msd
  2. Call GenerateConnectionString(ref _msd)
  3. Add a SQL command _msd.MySQLString = “SELECT * FROM <table>”;
  4. Call GetDataTable(_msd)

Of course, you have to add a reference to the library and add your ‘using’ statement. Also, make sure you have the two files the library uses with it: Interop.Adodb.dll and Interop.Msdasc.dll.

Conclusion

I have built a very simple program that uses this library so you can see how to use it yourself if you want. You are free to use it however you want. But please give me some feedback. Let me know what you think. Have a good one!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

lost in transition
Web Developer
United States United States
Member
I am a software, database, and gis developer. I love the challenge of learning new ways to code.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralDeploying an aplication using this codemembereliseobc20 Sep '07 - 9:42 
Hi,
 
I used the code described in this article, everything works fine when i am running in debug mode, but the problem arrives when I tried to deploy the application, the application can't display the dialog box, I checked that the dll's where included in the project, but still does not work.
 
Please help
GeneralRe: Deploying an aplication using this codememberjason_lakewhitney20 Sep '07 - 9:49 
Are making sure that the files:
Interop.ADODB.dll
Interop.MSDASC.dll
are being deployed too?
 

God Bless,
Jason


God doesn't believe in atheist but He still loves them and INITCOMMONCONTROLSEX too.

GeneralRe: Deploying an aplication using this codemembereliseobc20 Sep '07 - 13:44 
Yes they are,
 
Mi code is using the same objects but is a little bit different and is written in vb.net (see the sample code below)
 
I was doing more research and noticed that if I removed the following line it worked fine in both places the only problem is that by removing this line it does not retreives whatever the user has already selected in the connection window.
 
do you know if there is another way to prepopulate the connection builder window?
 
Thanks for answering my message
 
Removed Line:
_AdoDBconnection.ConnectionString = txtDBXDBConnectionString.Text
 
Sample code:
 
dim _dlInstance As MSDASC.DataLinksClass = New MSDASC.DataLinksClass
dim _AdoDBconnection As ADODB.ConnectionClass = New ADODB.ConnectionClass
 
_AdoDBconnection.ConnectionString = txtDBXDBConnectionString.Text
 
If _dlInstance.PromptEdit(_AdoDBconnection) Then
txtDBXDBConnectionString.Text = _AdoDBconnection.ConnectionString
End If
GeneralCheck the EntLibmemberFrank Olorin Rizzi6 Dec '06 - 7:27 
I'd reccomend taking a look at MS's EnterpriseLibrary (and its Data Access Application Block).
GeneralRe: Check the EntLibmemberjason_lakewhitney6 Dec '06 - 8:02 
The main purpose of this artical was to show how, with very little effort, you can run sql statements against a database.
 
Thank you for your comments,
Jason
 
Programmer: A biological machine designed to convert caffeine into code. * Developer: A person who develops working systems by writing and using software.
[^]

GeneralRe: Check the EntLibmemberMarc Leger6 Dec '06 - 11:36 
You are absolutley correct. In fact, let's turn off the Code Project. EntLib solves the worlds problems. It just hasn't had luck impeaching Bush.
GeneralRe: Check the EntLibmemberJoergen Sigvardsson30 Jul '07 - 13:14 
Laugh | :laugh: Laugh | :laugh: Laugh | :laugh:
 
--
Raaaaaaaaaaaaaaaaaaaaa!

GeneralRe: Check the EntLibmemberJan Seda6 Dec '06 - 11:52 
EntLib is overdesigned and we only use it to grab from its internals all good stuff and redesing it primary with performance in mind for our clients case by case Wink | ;)
Anyway EntLib has better general design but this solution in this article is so simple that can be useful for some specific cases. So this solution can be considered as good as simplicity is very important feature of smart software Wink | ;)
 
Regards,
Jan Seda
www.skilldrive.com
GeneralRe: Check the EntLibmemberFrank Olorin Rizzi6 Dec '06 - 13:16 
I didn't mean to insult the author of this article. If I did so, please forgive me.
I simply meant to bring to the readers' attention an alternative that, in my opinion, is a better answer *for nontrivial or enterprise-grade applications*. If you are here to write the database equivalent of Hello World, please don't let my comments get in your way.
When I read CodeProject I hardly assume everyone has read and tried out the same things; that is why I mentioned there is such a thing as the EntLib. If I had known that my comment was going to be read by such experts on the EntLib as it turned out, I would have been very quiet instead. Since I have the ear of such experts, though, let me take the opportunity: has anyone released any extension of the EntLib that we all might find useful ?
 
I completely agree that CodeProject is a very valuable repository, and I don't see why my original post would have prompted anyone to think that I don't value CodeProject or that I think the EntLib is the answer to all problems. heck, why else would I even be reading these pages ?
 
On the positive side, the author of this article points out that
 
"One of the biggest problems that a young programmer can face is OOP. What I mean is, we can be tempted to put too much code into a method (or a function) either to be able to see it in one place or just not knowing any better. Breaking up your code into logical sections helps a lot"
 
and that
 
You should "not hard code [the connection string] into your program"
 
Aside from that, though, I feel it is important to point out the shortcomings of the library presented. For instance: how do i extend it ?
 
F.O.R.
 
Incidentally, in regard to the appropriate format for connection strings for the various DBMSes, I think the best reference to link is http://www.connectionstrings.com/
 


GeneralRe: Check the EntLibmemberjason_lakewhitney7 Dec '06 - 3:00 
Frank Olorin Rizzi wrote:
I didn't mean to insult the author of this article.

 
I was not at all insulted by your comment. Like I had stated there can be many ways to get a job done.
 
Yes, in a way this is a "Hello World" type of artical. It is for someone who has never or has very little experiance with developing for a database.
 
Frank Olorin Rizzi wrote:
Incidentally, in regard to the appropriate format for connection strings for the various DBMSes, I think the best reference to link is http://www.connectionstrings.com/

 
This is a good comment and trust me I have used this site a few times before. Honestly, every time I develop on a DBMS that is new to me. The main point I was showing was another way to dynamicaly build a connection string and use it in your app. This is just another way to skin a cat and it gives your app the ability to be used on many different DBMS.
 
Thank you, everyone for your comments. Now this was me first artical, do you have any comments on the structure of the artical. What should I have done? What should I have NOT done? Also, I think we are very happy to have CodeProject as a valuible resouce.
 
Jason
 
Programmer: A biological machine designed to convert caffeine into code. * Developer: A person who develops working systems by writing and using software.
[^]

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 6 Dec 2006
Article Copyright 2006 by lost in transition
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid