c# - 在 C# winform 中使用 app.config 访问数据库连接字符串

标签 c# sql winforms database-connection app-config

我似乎无法访问我的 c# winforms 应用程序中的 app.config 数据库连接字符串。

app.config代码

   <connectionStrings>
      <add name="MyDBConnectionString" providerName="System.Data.SqlClient"
            connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
   </connectionStrings>  

C#代码:

SqlConnection conn = new SqlConnection();
conn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["MyDBConnectionString"];    

当我尝试 C# 代码时,我收到一条消息:
警告 1“System.Configuration.ConfigurationSettings.AppSettings”已过时:“ 此方法已过时,已被 System.Configuration!System.Configuration.ConfigurationManager.AppSettings 取代

但是,当我尝试使用时:

conn.ConnectionString = System.Configuration!System.Configuration.ConfigurationManager.AppSettings["MyDBConnectionString"];  

我得到一个错误:Only assignment, call, increment, decrement, and new object expressions can be used as a statement

最佳答案

这就是你所需要的:

System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

关于c# - 在 C# winform 中使用 app.config 访问数据库连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8476103/

相关文章:

c# - visual c# 2010 两个项目之间的通信

c# - 我应该如何在源代码管理中处理项目中的 secret 值?

c# - 如何将十六进制字符串转换为十六进制数

c# - 如何创建调用两个表的操作方法

mysql - 导入大型 SQL 文件

html - 使用html敏捷包忽略XPATH中的标签

c# - WinForms:将自定义 ToolStripMenuItem 添加到设计器中的 MenuStrip

sql - 我需要合并来自 SQL 选择查询的两个结果

sql - 如何在 Rails 中链接原始 SQL 查询或如何从 Rails 中的原始 SQL 查询返回 ActiveRecord_Relation?

c# - 使用 LINQ 在 Winforms 上查找控件?