ASP.NET: How to create a connection from a web.config ConnectionString?

后端 未结 3 767
Happy的楠姐
Happy的楠姐 2021-02-14 12:03

How do you construct a DbConnection based on a provider name?

Sample provider names

  • System.Data.SqlClient
  • System.Data.Ol
3条回答
  •  野性不改
    2021-02-14 12:06

    If you go this route, I think you'll want to use the DbProviderFactories class to get a DbProviderFactory that you can use to construct the connection. I haven't tried this code out, but I think it will work. It's possible that you may need to look up the provider name using the GetFactoryClasses method on the DbProviderFactories class and use the InvariantName.

    public DbConnection GetConnection(String connectionName)
    {
       //Get the connection string info from web.config
       ConnectionStringSettings cs= 
             ConfigurationManager.ConnectionStrings[connectionName];
    
       //documented to return null if it couldn't be found
       if (cs == null)
          throw new ConfigurationErrorsException("Invalid connection name \""+connectionName+"\"");
    
       //Get the factory for the given provider (e.g. "System.Data.SqlClient")
       DbProviderFactory factory = 
             DbProviderFactories.GetFactory(cs.ProviderName);
    
       //Undefined behaviour if GetFactory couldn't find a provider.
       //Defensive test for null factory anyway
       if (factory == null)
          throw new Exception("Could not obtain factory for provider \""+cs.ProviderName+"\"");
    
       //Have the factory give us the right connection object      
       DbConnection conn = factory.CreateConnection();
    
       //Undefined behaviour if CreateConnection failed
       //Defensive test for null connection anyway
       if (conn == null)
          throw new Exception("Could not obtain connection from factory");
    
       //Knowing the connection string, open the connection
       conn.ConnectionString = cs.ConnectionString;
       conn.Open()
    
       return conn;
    }
    

提交回复
热议问题