Establish Database Connection with MySQL in C# through App.config

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.

  1. <connectionStrings>  
  2.     <add name="myDatabaseConnection" connectionString="server=localhost;user=root;database=mydatabase;port=3306;password=mypassword;" />   
  3. </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.
  1. <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.
  1. ConfigurationManager.ConnectionStrings["myDatabaseConnection"].ConnectionString;  
Code:
  1. using MySql.Data.MySqlClient;  
  2. using System;  
  3. using System.Configuration;  
  4. namespace DatabaseConnection  
  5. {  
  6.     public static class DatabaseConnection  
  7.     {  
  8.         static MySqlConnection databaseConnection = null;  
  9.         public static MySqlConnection getDBConnection()  
  10.         {  
  11.             if (databaseConnection == null)  
  12.             {  
  13.                 string connectionString = ConfigurationManager.ConnectionStrings["myDatabaseConnection"].ConnectionString;  
  14.                 databaseConnection = new MySqlConnection(connectionString);  
  15.             }  
  16.             return databaseConnection;  
  17.         }  
  18.     }  
  19. }