您的位置:首页 > 其它

使用反射+抽象工厂的数据访问(3)

2010-12-31 00:22 232 查看
最后实现的代码如下:

所有数据库的基类(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;
}
本文出自 “Apprentice” 博客,请务必保留此出处http://apprentice.blog.51cto.com/2214645/1360590
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: