<b> </b><b>最後實作的代碼如下:</b>
<b> </b>
<b>所有資料庫的基類(DbProviderFactory.cs</b><b>)</b>
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);
}
/// 連接配接對象,此時無論是什麼資料庫連接配接,都是IDbConnection的子類,是以傳回的類型為IDbConnection
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;
本文轉自My_King1 51CTO部落格,原文連結:http://blog.51cto.com/apprentice/1360590,如需轉載請自行聯系原作者