How to connect to mysql using mysql connector via C# without actually installing the connector

Kalpak picture Kalpak · Jun 18, 2011 · Viewed 14.2k times · Source

We have a dot net 2.0 based C# product which uses Mysql as the data storage. When we install the mysql connector 6.3.6 on the XP/Win 7 machine, we are able to connect to the database from the C# code without any issues. But we are facing a problem while connecting to the mysql database when the mysql connector is actually not installed on the machine but is just present in the same directory as the executable. We don't want to install the connector on each and every machine we want the product to run on. We want the connectory dll to be used directly as we use any 3rd party dll (e.g logger) in our code.

Even when we copy the mysql.data.dll into the same directory where the exe is installed, it builds but does not connect to the database.

The error given is

Unable to find the requested .Net Framework Data Provider. It may not be installed Blockquote

Technical Information:

  • Mysql 5.0
  • C#
  • Dot Net framework 2.0
  • Mysql Connector 6.3.6 (same problem occurs with ver 6.0.3 of sql connector)
  • Win XP/Win 7

When we are using ASP.Net, we can specify the tag given below into the web.config, and we can connect to mysql database directly by putting the dll into the bin directory


<system.data>
  <DbProviderFactories>
    <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=5.0.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
  </DbProviderFactories>
</system.data>

Why can't we do the same thing in the C# for the Client Server application in the desktop environment.

Answer

Sergei Z picture Sergei Z · Jul 7, 2011

Try something like this (I didn't check any possible versions/configurations, but it works currently on my Vista x64 for MySql some 5.5... and .net connector 6.4.3.0 - using mysql.data.dll for v4 from .net/mono download).

Make sure the referenced mysql.data.dll assembly below is in your current directory.

using(var dt = new DataTable()) {
    dt.Columns.Add("Name");
    dt.Columns.Add("Description");
    dt.Columns.Add("InvariantName");
    dt.Columns.Add("AssemblyQualifiedName");
    dt.Rows.Add("Mysql something", 
        "mysql more", 
        "mysqlClient",
        "MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.4.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d");

    var f = DbProviderFactories.GetFactory(dt.Rows[0]);
    using(var conn = f.CreateConnection()) {
        conn.ConnectionString = "your string here";
        conn.Open();
        // and do your work here.
        Console.WriteLine(conn);
    }
}