微软企业库,可以连接不同的数据库。
Database db = DatabaseFactory.CreateDatabase();
运行时,会根据用户配置的不同,而创建不同的数据库实例。如果能够在程序运行后,动态修改数据库的连接字符串呢?本文提供了笔者的一种动态修改软企业库连接字符串的方法
/// <summary>
/// 读取数据库默认连接字符串
/// </summary>
/// <returns></returns>
private string ReadDefaultConnectString()
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection dataConfigurationSection = config.Sections["dataConfiguration"];
string defaultDatabase = (dataConfigurationSection as Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings).DefaultDatabase;
ConfigurationSection connectionConfigurationSection = config.Sections["connectionStrings"];
ConnectionStringsSection connectionStringsSection = connectionConfigurationSection as ConnectionStringsSection;
return connectionStringsSection.ConnectionStrings[defaultDatabase].ConnectionString;
}
/// <summary>
/// 保存数据库默认连接字符串
/// </summary>
/// <param name="connectString"></param>
private void SaveDefaultConnectString(string connectString)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection dataConfigurationSection = config.Sections["dataConfiguration"];
string defaultDatabase = (dataConfigurationSection as Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings).DefaultDatabase;
ConfigurationSection connectionConfigurationSection = config.Sections["connectionStrings"];
ConnectionStringsSection connectionStringsSection = connectionConfigurationSection as ConnectionStringsSection;
connectionStringsSection.ConnectionStrings[defaultDatabase].ConnectionString = connectString;
config.Save();
}
/// <summary>
/// 刷新数据库默认连接字符串
/// </summary>
private void RefreshConfig()
{
ConfigurationManager.RefreshSection("dataConfiguration");
ConfigurationManager.RefreshSection("connectionStrings");
}
转载于:https://www.cnblogs.com/shaowei/archive/2008/01/28/1056346.html