Click here to Skip to main content
15,846,211 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
hi friends,

In my project i write a connection like below,.

string MyConString = "SERVER=;" + "DATABASE=mcs_kiosk;" + "UID=root;" + "PASSWORD=;";
                  MySqlConnection connection = new MySqlConnection(MyConString);
                  MySqlCommand command = connection.CreateCommand();
                  MySqlDataReader Reader;
                  command.CommandText = "select * from mcs_hall";
                  Reader = command.ExecuteReader();
                  while (Reader.Read())
                      txt_Code.Text = Reader[1].ToString();
                      txt_Name.Text = Reader[2].ToString();

but this type connection load number of time,. so i want,

1. connection in xml or text file, for change MyConString.

2. program can read only one time the connection.

3. before the executing query, the connection want to check connection availability. if connection open execute query.

how to do this,. or give me any other idea.

thank u.
Updated 7-Mar-11 21:07pm

1 solution

Just few thoughts...

Put your connection string into to App.Config:

  <add name="mysql"
    providerName="MySql.Data.MySqlClient" />

You can initialize your connection like this:
ConnectionStringSettings connectString = ConfigurationManager.ConnectionStrings[connectionString];

if (connectionString == null)
    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, DatabaseServiceMessages.ConnectionStringNotFound, connectionString));

_factory = DbProviderFactories.GetFactory(connectString.ProviderName);
if (_factory == null)
    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, DatabaseServiceMessages.ConnectionStringNotFound, connectString.ProviderName));

_connection = _factory.CreateConnection();
_connection.ConnectionString = connectString.ConnectionString;

Encapsulate everything to a static class (you can use singleton design pattern):
public static class DbConnectionWrapper
  private static DbConnection _connection;

  public static DbConnection Connection
      if (_connection == null)
      // setup new connection
      // verify connection
      return _connection;
Share this answer
Sagotharan Jagadeeswaran 8-Mar-11 23:52pm    
thank u friend,. how to check the connection availability in application.
voloda2 9-Mar-11 4:48am    
what about a simple select, which should always work (such as "select 1")? If a DbException is thrown, try reconnect...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900