使用c#以编程方式更改mysql连接字符串

时间:2012-06-08 04:10:22

标签: c# asp.net app-config

我想在运行时更改app.setting连接字符串。我有一些代码来改变它,但我不能这样做。运行时没有出现错误。但执行期间没有变化。

这是我的部分代码:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="Punch_Uploader.Properties.Settings.testConnectionString"
            connectionString="server=localhost;User Id=root;password=test123;database=test"
            providerName="MySql.Data.MySqlClient" />
        <add name="Punch_Uploader.Properties.Settings.testConnectionString1"
            connectionString="server=172.23.2.52;User Id=root;password=test123;database=test"
            providerName="MySql.Data.MySqlClient" />
    </connectionStrings>
</configuration>

并且:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Add(
    new ConnectionStringSettings("Punch_Uploader.Properties.Settings.testConnectionString2", 
        String.Format(
            "server={0};Port={1}; database={2};User Id={3};password={4};providerName={5}", 
            "172.23.2.32", "3306", "test", "root", "test123", "MySql.Data.MySqlClient")
        )
);
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings"); 

MessageBox.Show(ConfigurationManager
    .ConnectionStrings["Punch_Uploader.Properties.Settings.testConnectionString2"]
    .ConnectionString);

以上代码对我不起作用....

请帮我解决这个问题。

4 个答案:

答案 0 :(得分:3)

ConnectionStringSettings settings =
    ConfigurationManager.ConnectionStrings["Punch_Uploader.Properties.Settings.testConnectionString"];

string connectString = settings.ConnectionString;    

SqlConnectionStringBuilder builder =
        new SqlConnectionStringBuilder(connectString);

builder.DataSource = "172.23.2.52:3306";
builder.InitialCatalog = "test";
builder.UserID = "root";
builder.Password = "test123";

正如前面回答的评论中所提到的,我可以确认这个方法是有效的,因为我之前使用它来在不同的数据库环境之间切换。

答案 1 :(得分:0)

连接字符串是只读的。 要更改连接字符串,您需要手动将更改保存回配置文件,这将导致应用程序重新启动。

编辑:快速搜索,我发现了这个(可能会有所帮助):connection string at runtime

答案 2 :(得分:0)

试试这个,

 Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");
 ConnectionStringsSection section = webConfig.GetSection("connectionStrings") as            
                                              ConnectionStringsSection;
 if (section != null)
 {
   section.ConnectionStrings["NameTheCnStr"].ConnectionString = "New Connection string here";
   webConfig.Save();
  }

答案 3 :(得分:0)

尝试此代码

 private void UpdateConnectionString(string ConfigPath)
 {
     XmlDocument xmlDocument = new XmlDocument();
     xmlDocument.Load(ConfigPath);
      XmlNode parentNode = xmlDocument.DocumentElement;
     if (parentNode.Name == "connectionStrings")
     {
        foreach (XmlNode childNode in parentNode.ChildNodes)
        {
           if (childNode.Name == "add" && childNode.Attributes["name"].Value=="Punch_Uploader.Properties.Settings.testConnectionString")
           {
             string sqlConnectionString =childNode.Attributes["connectionString"].Value;
             SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(sqlConnectionString);
             sqlBuilder.InitialCatalog = "yourDatabaseName";
             sqlBuilder.IntegratedSecurity = true;
             sqlBuilder.Password = "";

             //Change any other attributes using the sqlBuilder object
             childNode.Attributes["connectionString"].Value = sqlBuilder.ConnectionString;
           }
        }
      }
      xmlDocument.Save(ConfigPath);
  }

configPath是来自Web.config

的连接字符串的路径
string configPath  = ConfigurationManager.ConnectionStrings["Punch_Uploader.Properties.Settings.testConnectionString"].ConnectionString;