When we create the new project (Window form application in my last blog customize form) the App.config file is automatically created, if not there then create it, generally it is a XML file with “.config” extension. It contents <?xml ?> tag with vertion and encoding and <configuration></ configuration > tag which defines the supported runtime verson of .net framework. Let’s have a lock.
Now we have to put connection string in the App.config file.
- <connectionStrings>
- <add name="myDatabaseConnection" connectionString="server=localhost;user=root;database=mydatabase;port=3306;password=mypassword;" />
- </connectionStrings>
It starts with <connectionStrings> tag and ends with </connectionStrings> and this connection string tag should be placed between <configuration></ configuration > tag. In between <connectionStrings> </connectionStrings> tag add.
- <add name=”YourStringName” connetionString=”connection strig”/>
Now it’s time to retrieve the connection string from App.config. Create a class file for database connection and retrieve the connection string by using “ConfigurationManager”.
To get the connection string we should have to provide “ConfigurationManager” the name we have configured in App.config file.
E.g.
- ConfigurationManager.ConnectionStrings["myDatabaseConnection"].ConnectionString;
Code:
- using MySql.Data.MySqlClient;
- using System;
- using System.Configuration;
- namespace DatabaseConnection
- {
- public static class DatabaseConnection
- {
- static MySqlConnection databaseConnection = null;
- public static MySqlConnection getDBConnection()
- {
- if (databaseConnection == null)
- {
- string connectionString = ConfigurationManager.ConnectionStrings["myDatabaseConnection"].ConnectionString;
- databaseConnection = new MySqlConnection(connectionString);
- }
- return databaseConnection;
- }
- }
- }