I am currently creating a C# application that supports MySQL and MSSQL databases. The problem I am having is with my wrapper. I have my code working for MySQL, but I am having issues modifying it to support multiple databases.
If you take a look at a stripped down version of my code you will see I have a dbConn object of type DBMySQL, which is fine if I only want MySQL Support. I need modify DBMySQL to be something generic so that I can run dbConn = new DBMySQL(…) and dbConn = DBMSSQL(…) and then I can simply call dbConn.SomeMethod() and have it work on the appropriate database. I would prefer to keep this same setup as much as possible as I have other things in my DBMySQL and DBMSSQL classes for bulk inserting into databases and specific error checking.
I was thinking / trying to declare something like Object dbConn, then manipulating that, but that did not go so well. Then I tried to use an enum class of object types, but I had issues with that as well. I know there are many third party libraries that do all of this but I would prefer to use my own code.
Does anyone have any suggestions how I might modify my DBWrapper to solve this problem?
//WRAPPER CLASS THAT CALLS DBMySQL, ISSUE IS I NOW NEED TO SUPPORT
//DBMSSQL as well, not just DBMySQL
class DBWrapper
{
DBMySQL dbConn;
public DBWrapper(...,string type)
{
if(type.Equals("MySQL")
{
dbConn = new DBMySQL(...);
}
//NEED TO REWORK TO SUPPORT THIS BELOW!!
else if(type.Equals("MSSQL")
{
//NEED TO MODIFY TO SUPPORT MSSQL
//ISSUE IS DbConn is of type DBMySQL
//SO I CANNOT GO
// DbConn = new DBMSSQL(...);
// any ideas?
}
}
public void setQuery(string myquery)
{
dbConn.setQuery(myquery);
}
}
class DBMySQL
{
public string dbinfo;
string query;
public DBMySQL(...)
{
dbinfo = ...;
}
public void setQuery(...)
{
query = myquery;
}
}
//NEED TO RE-WORK WRAPPER TO SUPPORT THIS
class DBMSSQL
{
public string dbinfo;
string query;
public DBMSSQL(...)
{
dbinfo = ...;
}
public void setQuery(...)
{
query = myquery;
}
}
At this point I would appreciate any help at all, so if you are viewing this post and have an idea, please let me know as I have already spent all day on this.
What you need is to create interface which would describe what you want your data access classes to do.
E.g. from your sample
At this point you will be able to do this:
Having in mind that you are new to this it may not be useful to suggest that you take a look at NHibernate or Castle ActiveRecord and Castle Windsor. But have them in mind for future.