最后实现的代码如下:
所有数据库的基类(DbProviderFactory.cs)
using System;
using System.Data;
using System.Data.Common;
using System.Reflection;
namespace SplendidCRM
{
public class DbProviderFactory
{
protected string m_sConnectionString ;
protected Assembly m_asmSqlClient ;
protected System.Type m_typSqlConnection ;
protected System.Type m_typSqlCommand ;
protected System.Type m_typSqlDataAdapter ;
protected System.Type m_typSqlParameter ;
protected System.Type m_typSqlBuilder ;
/// <summary>
/// DbProviderFactory构造函数,用一系列参数指定实际使用的是什么数据库
/// </summary>
public DbProviderFactory(string sConnectionString, string sAssemblyName, string sConnectionName, string sCommandName, string sDataAdapterName, string sParameterName, string sBuilderName)
{
m_sConnectionString = sConnectionString;
// 使用反射
m_asmSqlClient = Assembly.LoadWithPartialName(sAssemblyName);
if ( m_asmSqlClient == null ) throw(new Exception("无法载入 " + sAssemblyName));
m_typSqlConnection = m_asmSqlClient.GetType(sConnectionName );
m_typSqlCommand = m_asmSqlClient.GetType(sCommandName);
m_typSqlDataAdapter = m_asmSqlClient.GetType(sDataAdapterName);
m_typSqlParameter = m_asmSqlClient.GetType(sParameterName);
}
/// <summary>
/// 连接对象,此时无论是什么数据库连接,都是IDbConnection的子类,所以返回的类型为IDbConnection
/// </summary>
public IDbConnection CreateConnection()
{
Type[] types = new Type[1];
types[0] = Type.GetType("System.String");
ConstructorInfo info = m_typSqlConnection.GetConstructor(types);
object[] parameters = new object[1];
parameters[0] = m_sConnectionString;
IDbConnection con = info.Invoke(parameters) as IDbConnection;
if ( con == null )
throw(new Exception(" 无法创建连接Connection"));
return con;
}