简体   繁体   中英

Use and call the connection string in the forms/ c#

I'm building desktop application using c# , I put the connection string in the app.config file like this

 <connectionStrings>
        <add name="ComputerManagement" 
        connectionString="Provider=Microsoft.ACE.OLEDB.12.0; Data Source=...;Initial Catalog=Computersh;Integrated Security=True"/>
      </connectionStrings>

How I can call the connection string in the forms ?

You can get the connection string with ConfigurationManager :

using System.Configuration;
var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];

But you'll still need to use something to connect to the database with it, such as SqlConnection : http://msdn.microsoft.com/en-gb/library/system.data.sqlclient.sqlconnection.aspx

using System.Configuration;
using System.Data.SqlClient;

var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];

if (connection != null) 
{
    using (var sqlcon = new SqlConnection(connection.ConnectionString))
    {
        ...
    }
}

Reference System.Configuration and use

System.Configuration.ConfigurationManager
      .ConnectionStrings["ComputerManagement"].ConnectionString

Like this:

var constring = ConfigurationManager.ConnectionStrings["ComputerManagement"].ConnectionString;

Also you have to add this using System.Configuration; :)

Using the ConfigurationManager should suffice:

var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];

Then, check for null , before accessing the actual string:

if (connection != null) {
  var connectionString = connection.ConnectionString;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM