user
user

Reputation: 735

Generic Database Connection C#

Im working on this application that will transfer data from a database another application. But I am trying to get the database functionality working.

I need to be able to connect any type of database (Oracle, SQL, etc...) to the app because my user base uses different databases.

I was following the tutorial on http://www.splinter.com.au/using-generic-database-providers-with-c/ and I'm having trouble connecting my test MySQL database to it.

Here is my sample code:

static void Main(string[] args)
{
    string connection = "SERVER=localhost;UID=root;PASSWORD=toor";
    string provider = "MySql.Data.MySqlClient";

    using (DbConnection conn = (DbConnection)Activator.CreateInstance(Type.GetType(provider), connection))
    {
        conn.Open();
        string sql = "SHOW DATABASES";
        using(DbCommand comm = conn.CreateCommand())
        {
            comm.CommandText = sql;
            using(DbDataReader reader = comm.ExecuteReader())
            {
                while(reader.Read())
                {
                    string owner = reader.GetString(0);
                    Console.WriteLine("{0}", owner);
                }
            }
        }
    }
    Console.ReadLine();
}

The error I'm getting is ArgumentNullException and I can see that in the debugger that conn is null. I'm not sure why it's not working though. I've used that connection string and provider in an app that uses the MySQL library. Could it be that my connection string needs to be changed? If so, what do I change it to?

Also, I don't want to add a Database to the connection string, that is chosen later.

Upvotes: 4

Views: 2217

Answers (1)

C.Evenhuis
C.Evenhuis

Reputation: 26446

I guess Type.GetType(provider) returns null because you're specifying the type's Fullname

"MySql.Data.MySqlClient"

instead of its AssemblyQualifiedName

"MySql.Data.MySqlClient, MySql.Data"

Specifying a type name without an assembly name only works if the type is in the currently executing assembly or mscorlib.

If you are trying to load the assembly from the GAC you'll have to include the Version, Culture and PublicKeyToken parameters too, ie:

"MySql.Data.MySqlClient.MySqlConnection, MySql.Data, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"

This depends on the version of the driver.

Upvotes: 3

Related Questions