如何将 ADO.NET DbProviderFactory 与 MySQL 一起使用?

2022-01-23 00:00:00 mysql ado.net dbproviderfactories

如何将 ADO.NET DbProviderFactory 与 MySQL 一起使用?

How can I use ADO.NET DbProviderFactory with MySQL?

推荐答案

首先,你必须安装 MySQL .Net 连接器.

MySQL Provider 工厂具有不变的名称MySql.Data.MySqlClient".下面是一些示例 C# 代码,它检索本地测试数据库中的所有表名并将它们粘贴到列表框中以响应按钮单击.

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)
{
    var dbf = DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
    using (var dbcn = dbf.CreateConnection())
    {
        dbcn.ConnectionString = "Server=localhost;Database=test;Uid=test;Pwd=test;";
        dbcn.Open();
        using (var dbcmd = dbcn.CreateCommand())
        {
            dbcmd.CommandType = CommandType.Text;
            dbcmd.CommandText = "SHOW TABLES;";
            using (var dbrdr = dbcmd.ExecuteReader())
            {
                while (dbrdr.Read())
                {
                    listBox1.Items.Add(dbrdr[0]);
                }
            }
        }
    }
}

相关文章