ado.net2.0 增强了数据提供程序的架构,并引入了工厂类,每个.net数据提供程序包括一个派生于基类DbProviderFactory的工厂类,工厂类表示该提供程序特有的各种服务的入口点。下面列出了一个工厂类的主要方法:

CreateCommand 返回一个提供程序特有的命令对象

CreateCommandBuilder  返回一个提供程序特有的命令创建者对象

CreateConnection  返回一个提供程序特有的连接对象

CreateDataAdapter  返回一个提供程序特有的适配器对象

CreateParameter  返回一个提供程序特有的参数对象

如何获得一个特有的数据提供程序的工厂呢?通过使用DbProviderFactories新类就可以,该类有几个静态方法,举例如下:

DbProviderFactory f=DbProviderFactories.GetFactory("System.Data.SqlClient");

GetFactory()方法取一个字符串,该字符串表示提供程序的恒定名称,在注册提供程序的配置文件中,该名称是为每个提供程序硬编码的。根据约定,提供程序的名称等于其唯一的命名空间。

GetFactory() 列举所有的注册提供程序,并为匹配的恒定名称获得程序集和类名信息,该工厂类不是直接实例化的,而是由该方法使用映像(reflection)获取工厂类的静态属性Instance的值。该属性返回将要使用的工厂类的实例。一旦有了工厂对象,就可以调用其中的方法了。

下面说明了SqlClientFactory类(sql server .net 数据提供程序的工厂类)的CreateConnection方法内部的实现。

 

数据提供程序工厂模型Public DbConnection CreateConnection()
数据提供程序工厂模型
{
数据提供程序工厂模型       
return new SqlConnection();
数据提供程序工厂模型}

数据提供程序工厂模型

如下实例是获取所有的提供程序列表:

数据提供程序工厂模型    protected void Page_Load(object sender, EventArgs e)
数据提供程序工厂模型    
{
数据提供程序工厂模型        
//DbProviderFactories.
数据提供程序工厂模型        
//DbProviderFactory f = DbProviderFactories.GetFactory("System.Data.SqlClient");
数据提供程序工厂模型
        
数据提供程序工厂模型        DataTable providers 
= DbProviderFactories.GetFactoryClasses();
数据提供程序工厂模型        GridView1.DataSource 
= providers;
数据提供程序工厂模型        GridView1.DataBind();
数据提供程序工厂模型    }

 

 

使用多数据库的一个实例

 

 

数据提供程序工厂模型    protected void Button1_Click(object sender, EventArgs e)
数据提供程序工厂模型    
{
数据提供程序工厂模型        
string provider = this.provider.Text;
数据提供程序工厂模型        
string constring = this.connString.Text;
数据提供程序工厂模型        
string commandtext = this.commandtext.Text;
数据提供程序工厂模型
数据提供程序工厂模型        DbProviderFactory fact 
= DbProviderFactories.GetFactory(provider);
数据提供程序工厂模型
数据提供程序工厂模型        DbConnection conn 
= fact.CreateConnection();
数据提供程序工厂模型        conn.ConnectionString 
= constring;
数据提供程序工厂模型
数据提供程序工厂模型        DbDataAdapter adapter 
= fact.CreateDataAdapter();
数据提供程序工厂模型        adapter.SelectCommand 
= conn.CreateCommand();
数据提供程序工厂模型        adapter.SelectCommand.CommandText 
= commandtext;
数据提供程序工厂模型
数据提供程序工厂模型        DataTable dt 
= new DataTable();
数据提供程序工厂模型        adapter.Fill(dt);
数据提供程序工厂模型
数据提供程序工厂模型        
this.GridView2.DataSource = dt;
数据提供程序工厂模型        GridView2.DataBind();
数据提供程序工厂模型
数据提供程序工厂模型    }

相关文章:

  • 2022-01-18
  • 2022-12-23
  • 2021-10-16
  • 2021-04-02
  • 2021-11-08
  • 2021-07-23
  • 2022-12-23
猜你喜欢
  • 2022-01-17
  • 2022-12-23
  • 2022-12-23
  • 2021-11-12
  • 2021-07-17
  • 2021-08-09
相关资源
相似解决方案