【问题标题】:Can you change the ConnectionString configuration value at runtime?您可以在运行时更改 ConnectionString 配置值吗?
【发布时间】:2011-01-25 12:15:08
【问题描述】:

是否可以在运行时更改 app.config 中的 ConnectionString 值?根据the MSDN documentation,它应该可以作为 ConnectionString 属性“获取或设置连接字符串”。

我的代码如下所示:

ConnectionStringSettings mainConnection = ConfigurationManager.ConnectionStrings["mainConnection"];
mainConnection.ConnectionString = "Data Source=SERVER;Initial Catalog=" + NewDatabaseName + ";Integrated Security=True";

我收到的错误是这样的:“未处理的异常:System.Configuration.ConfigurationErrorsException:配置是只读的。”

【问题讨论】:

  • 您能解释一下为什么要在运行时切换数据库/连接字符串吗?
  • 我正在将内容从旧版本的库迁移到新版本的库 - 两个版本都使用相同的连接字符串名称,但我想从一个数据库读取并写入另一个数据库。
  • 我刚刚意识到我在帖子中写了 web.config,我的意思是 app.config(已更新以反映更改)。

标签: .net sql


【解决方案1】:

connectionStrings-Section 是只读的。 我只需要在会话期间进行更改,例如使用只读帐户进行数据库查询,并在验证后使用授权帐户进行更新/修改操作。

所以我的解决方案是appSettings-Section的connectionString,可以在运行时修改。

在 Web.config 中: <appSettings> <add key="dbconnectionstr" value="Database=...;Host=...;Password=...;Username=..."/> </appSettings>

在 SQLDataSource: <asp:SqlDataSource ID="datasource1" runat="server" ConnectionString="<%$ AppSettings:dbconnectionstr %>" .... </asp:SqlDataSource>

并在代码: WebConfigurationManager.AppSettings["dbconnectionstr"] = newonnectionString;

【讨论】:

    【解决方案2】:

    不建议在运行时使用 web.config 更改连接字符串。
    我建议在不同的文件中维护这些连接并实现一个文件观察器来验证这些参数的值是否已更改。

    【讨论】:

      【解决方案3】:

      我猜您看到的是编译器错误,而不是运行时错误。您正在使用的类是从您的应用程序设置中生成的方法,并且生成的属性在属性上只有一个 getter,而没有 setter。这就是您收到该错误的原因。

      要更改属性,您需要使用 Configuration 类,并使用 AppSettings 属性,传入字符串作为键。然后就可以调用 Configuration.Save 方法了。

      【讨论】:

      • 是ConnectionStringSetting,不是AppSetting,绝对不是编译错误。奇怪的是文档说我可以设置这个值。
      【解决方案4】:
      Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); 
          myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text; 
          myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text; 
          myConfiguration.Save(); 
      

      参考:http://www.beansoftware.com/ASP.NET-Tutorials/Modify-Web.Config-Run-Time.aspx

      【讨论】:

      • +1:只是一个小修改:如果您想再次从配置文件中重新读取新值而不需要重新启动应用程序,请在保存后通过调用以下方法刷新文件: System.Configuration.ConfigurationManager.RefreshSection("connectionStrings");
      • 这行得通,虽然我在控制台应用程序中,所以我不得不使用不同的行:Configuration myConfiguration = ConfigurationManager.OpenExeConfiguration(exeFilePath);请注意,这确实会更改物理配置文件。
      【解决方案5】:

      不确定为什么要在运行时不断更改 web.config(不推荐),但请查看此处了解更多信息。

      Writing to .NET Web.config

      这里的主要内容是您的 web.config 需要对运行 ASPNET 进程的帐户具有读写权限。

      【讨论】:

      • 不知道为什么这被否决了。您提供了一项建议,指出这不是好的做法,并且还提供了关于 OP 要求的问题的进一步阅读。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多