dbproviderfactories该类有几个静态方法

sql server提供程序工厂对象的方法

dbproviderfactory fact=dbproviderfactories.getfactory(“system.data.client”);

getfactory 方法接收一个字符串,该字符串代表提供程序的名称。这个名称位于machine.config文件中,他会对所有已注册的提供程序进行枚举,返回与该名称匹配的程序集和类名信息。工厂类并不会直接被实例化(即所谓的单例模式)。一旦获得工厂对象,就可以调用如下方法

createcommand 返回代表提供程序特定的命令对象

createcommandbuilder 返回提供程序特定的命令生成器对象

crateconnection 返回提供程序特定的连接对象

createdataadapter 返回提供程序特定的数据适配器对象

createparameter 返回提供程序特定的参数对象

若要创建提供程序工厂,必须提供连接字符串和提供程序名称。此示例演示如何通过以“system.data.providername”固定格式传递提供程序名称来从应用程序配置文件中检索连接字符串。代码循环访问 connectionstringsettingscollection。成功时代码返回 providername;否则返回 null。如果提供程序有多项,则返回找到的第一项。

按提供程序名称检索连接字符串

// retrieve a connection string by specifying the providername.
// assumes one connection string per provider in the config file.
static string getconnectionstringbyprovider(string providername)
{
    // return null on failure.
    string returnvalue = null;

    // get the collection of connection strings.
    connectionstringsettingscollection settings =
        configurationmanager.connectionstrings;

    // walk through the collection and return the first 
    // connection string matching the providername.
    if (settings != null)
    {
        foreach (connectionstringsettings cs in settings)
        {
            if (cs.providername == providername)
                returnvalue = cs.connectionstring;
            break;
        }
    }
    return returnvalue;
}


创建 dbproviderfactory 和 dbconnection

示例演示如何通过以“system.data.providername”格式传递提供程序名称和连接字符串来创建 dbproviderfactory 和 dbconnection 对象。 成功时返回 dbconnection 对象;出错时返回 null(在 visual basic 中为 nothing)。

代码通过调用 getfactory 获取 dbproviderfactory。 然后,createconnection 方法创建 dbconnection 对象并将 connectionstring 属性设置为连接字符串。、

// given a provider name and connection string, 
// create the dbproviderfactory and dbconnection.
// returns a dbconnection on success; null on failure.
static dbconnection createdbconnection(
    string providername, string connectionstring)
{
    // assume failure.
    dbconnection connection = null;

    // create the dbproviderfactory and dbconnection.
    if (connectionstring != null)
    {
        try
        {
            dbproviderfactory factory =
                dbproviderfactories.getfactory(providername);

            connection = factory.createconnection();
            connection.connectionstring = connectionstring;
        }
        catch (exception ex)
        {
            // set the connection to null if it was created.
            if (connection != null)
            {
                connection = null;
            }
            console.writeline(ex.message);
        }
    }
    // return the connection.
    return connection;
}

这样如果我们要更改只需在配置文件中更改相应的连接字符串,以及更改createdbconnection的providername参数即可。