Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple SQL Server connection strings in app.config file

I'm interested in displaying in a Windows Forms app a list of N radio buttons for the user to choose a target database server. I would like to add the SQL Server connection strings in the app.config file, so they are read by the app at runtime and rendered in the windows form as radio buttons.

At first I thought of using a delimiter to separate the connections

  <appSettings>
    <add key="ConnectionString" value="connection1|user id=user;password=123;server=10.0.0.1;database=myDatabase;connection timeout=30|connection2|user id=user;password=123;server=10.0.0.2;database=myDatabase;connection timeout=30"/>
</appSettings>

And then split the key value pairs.

Is it possible to do this in a different way?

like image 512
Benjamin Ortuzar Avatar asked Oct 07 '09 08:10

Benjamin Ortuzar


People also ask

Where are SQL connection strings stored?

Connection strings can be stored as key/value pairs in the connectionStrings section of the configuration element of an application configuration file.

How set SQL connection string in web config?

<connectionStrings> <add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System. Data. SqlClient" />

Where should you store the connection string information?

Connection strings in configuration files are typically stored inside the <connectionStrings> element in the app. config for a Windows application, or the web. config file for an ASP.NET application.


1 Answers

To find all defined connection strings from your app.config, use the ConfigurationManager (from System.Configuration).

It has an enumeration: ConfigurationManager.ConnectionStrings which contains all entries in your <connectionStrings>.

You can loop over it with this code:

foreach(ConnectionStringSettings css in ConfigurationManager.ConnectionStrings)
{
   string name = css.Name;
   string connString = css.ConnectionString;
   string provider = css.ProviderName;
}

The Name is just the symbolic name you give your connection string - it can be anything, really.

The ConnectionString is the connection string itself.

The ProviderName is the name of the provider for the connection, e.g. System.Data.SqlClient for SQL Server (and others for other database system). If you omit the providerName= attribute from your connection string in config, it defaults to SQL Server (System.Data.SqlClient).

Marc

like image 59
marc_s Avatar answered Sep 20 '22 07:09

marc_s