SqlConnection 和 SqlCEConnection 都扩展了 System.Data.Common.DbConnection,因此将“blah”声明为 DbConnection,您将能够使用相同的方法和属性。
要实际创建正确的连接类型,请使用 System.Data.Common.DbProviderFactories 和 System.Data.Common.DbProviderFactory 类。例如:
DbProviderFactory providerFactory = DbProviderFactories.GetFactory("The Provider Name");
using (DbConnection connection = providerFactory.CreateConnection())
{
connection.ConnectionString = "The Connection String";
connection.Open();
// Use the "connection" object here
}
对于“提供者名称”,您可以根据数据库类型输入“System.Data.SqlClient”或“System.Data.SqlServerCe”。然后对于“连接字符串”,您将为提供程序类型输入正确的连接字符串。
编辑:此技术适用于您的 App.config 文件和 System.Configuration.ConfigurationManager 类。例如,如果您的 App.config 文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="TheConnectionString" providerName="System.Data.SqlClient" connectionString="Blah Blah Blah" />
</connectionStrings>
</configuration>
然后您可以像这样访问这些配置设置:
DbProviderFactory providerFactory = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings["TheConnectionString"].ProviderName);
using (DbConnection connection = providerFactory.CreateConnection())
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["TheConnectionString"].ConnectionString;
connection.Open();
// Use the "connection" object here
}