如何使用C#中的app.config文件定义连接字符串

 刘美娥94662 发布于 2023-02-07 10:50

目前我在我的C#代码中手动定义我的连接字符串:

string ConnectionString = "Data Source=C;Initial Catalog=tickets;Integrated Security=True";
SqlConnection Conn = new SqlConnection(ConnectionString);
Conn.Open();

在我的项目中,我有一个app.config文件,我可以看到它有一个连接字符串.它看起来像这样:






    


如何根据与我的应用程序相同的文件夹中的app.config文件定义连接字符串?

3 个回答
  • 用此修改您的应用程序

    App.config文件

    <?xml version="1.0"?>
      <configuration>
        <configSections>
        </configSections>
        <connectionStrings>
             <add name="ticketNotification.Properties.Settings.ticketsConnectionString"
                  connectionString="Data Source=C;Initial Catalog=tickets;Integrated Security=True" providerName="System.Data.SqlClient" />
        </connectionStrings>
        <startup>
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
        </startup>
      </configuration>
    

    这是你的代码隐藏文件.您需要使用System.ConfigurationNamespace.System.Configurationnamespace包含ConfigurationManager用于从app.config/web.config文件中获取连接字符串的类.

    由于这是一个Windows应用程序,因此您可以App.config在其中定义连接字符串.要获取配置文件中定义的连接字符串,您需要在所需的事件处理程序中使用下面的代码行

    将此命名空间添加到您的代码(ex :) Form1.cs文件中

    using System.Configuration;
    

    在eventhandler里面添加/修改这些代码

      string myConnectionString = ConfigurationManager.ConnectionStrings["ticketNotification.Properties.Settings.ticketsConnectionString"].ConnectionString;
    
      using(SqlConnection Conn = new SqlConnection(myConnectionString))
      {
         Conn.Open();
         //Define the SQL query need to be executed as a string
    
        //Create your command object
    
        //Create Dataset,Dataadapter if required
    
        //add parameters to your command object - if required
    
       //Execute your command
    
       //Display success message
     }
    

    2023-02-07 10:52 回答
  • 要从app.config文件获取连接字符串,请使用位于System.Configuration命名空间中的类ConfigurationManager.

    要按名称获取连接字符串并基于它创建连接,可以使用以下代码:

    SqlConnection conn = new SqlConnection(
          ConfigurationManager.ConnectionStrings[
             "ticketNotification.Properties.Settings.ticketsConnectionString"]
                 .ConnectionString);
    

    您可以在这里阅读更多相关信息(MSDN文档):http://msdn.microsoft.com/en-us/library/ms254494(v = vs.110) .aspx

    确保您的项目包含对System.Configuration的引用,否则ConfigurationManager将无法在System.Configuration命名空间中使用.

    问候.

    2023-02-07 10:54 回答
  • 首先通过右键单击"引用"并选择"添加引用"来添加对System.Configuration的引用.然后用

    Using System.Configuration
    
    // within the class here
    
    ConfigurationManager.ConnectionStrings["ticketNotification.Properties.Settings.ticketsConnectionString"].ConnectionString;
    

    显然,您需要在括号中输入连接字符串的名称.

    2023-02-07 10:54 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有