有时间研究了一下.net framework的DbProviderFactory (ADO.NET), namespace:System.Data.Common;
使用
DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
connection = factory.CreateConnection();
可以很方便的创建不同类型的数据连接
首先在config文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<clear/>
<add name="NorthwindSQL"
providerName="System.Data.SqlClient"
connectionString=
"Data Source=.;Initial Catalog=Northwind;Integrated Security=true"/>
<add name="NorthwindAccess"
providerName="System.Data.OleDb"
connectionString=
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Northwind.mdb;"/>
<add name="NorthwindMySql"
connectionString=
"Server=172.29.131.27;Port=3311;DataBase=comctl;Persist Security Info=False;User ID=root;Password=123456;Allow Zero Datetime=true;"
providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
<appSettings>
<add key="Connection" value="NorthwindMySql"/>
</appSettings>
<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.2.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
</DbProviderFactories>
</system.data>
</configuration>
如果本地已经安装mysql,则不需要注册此配置信息
CS
public static DataTable GetCategories()
{
DataTable table = new DataTable();
string connName = System.Configuration.ConfigurationManager.AppSettings["Connection"];
string connectionString = ConfigurationManager.ConnectionStrings[connName].ConnectionString;
string providerName = ConfigurationManager.ConnectionStrings[connName].ProviderName;
// Create the DbProviderFactory and DbConnection.
DbProviderFactory factory =
DbProviderFactories.GetFactory(providerName);
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
using (connection)
{
// Define the query.
string queryString =
"SELECT * FROM Categories";
// Create the DbCommand.
DbCommand command = factory.CreateCommand();
command.CommandText = queryString;
command.Connection = connection;
// Create the DbDataAdapter.
DbDataAdapter adapter = factory.CreateDataAdapter();
adapter.SelectCommand = command;
// Fill the DataTable.
adapter.Fill(table);
}
return table;
}
// Retrieve the installed providers and factories.
DataTable table = DbProviderFactories.GetFactoryClasses();
得到本机所有providers
深入理解http://technet.microsoft.com/zh-cn/office/wda6c36e.aspx