tags:

views:

960

answers:

1

How to use ADO.NET DbProviderFactory with MySQL?

+3  A: 

First, you have to install the MySQL .Net Connector.

The MySQL Provider factory has the invariant name "MySql.Data.MySqlClient". Below is some example C# code that retrieves all the table names in the local test database and sticks them in a listbox in response to a button click.

private void button1_Click(object sender, EventArgs e)
{
    DbProviderFactory dbf = DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
    using (DbConnection dbcn = dbf.CreateConnection())
    {
        dbcn.ConnectionString = "Server=localhost;Database=test;Uid=test;Pwd=test;";
        dbcn.Open();
        using (DbCommand dbcmd = dbcn.CreateCommand())
        {
            dbcmd.CommandType = CommandType.Text;
            dbcmd.CommandText = "SHOW TABLES;";
            using (DbDataReader dbrdr = dbcmd.ExecuteReader())
            {
                while (dbrdr.Read())
                {
                    listBox1.Items.Add(dbrdr[0]);
                }
            }
        }
    }
}
Ken Keenan
Thanks a lot buddy!