Click here to Skip to main content
15,887,355 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am doing Project in C#.net with Sql server. Here I am Opening connection in each and every Click event of form. It's deferring little bit while executing.. So how to write code to make global connection in form load event or using Class concept.
Posted

The first thing is: Don't do it.

You may get away with it for a project, but SQLServer connections are scarce resources in the real world, and any app holding a connection open globally will seriously annoy database administrators as the connection is not available for other users - this gets expensive!

Always create connection, use connection, close and dispose connection as quickly as possible.

Are you sure it is the connection that is taking time, not your command?
 
Share this answer
 
Use Class and create a public function for creating data connection
here is the code

C#
public bool OpenConnection(MySqlConnection Conn)
    {
        String connStr = "your connection string"
        if (Conn == null)
        {
            errorMessage = "Connection Object doesn't exists. Internal Error";
            return false;
        }
        if (Conn.State != ConnectionState.Open)
        {
            try
            {
                Conn.ConnectionString = connStr;
                Conn.Open();
                return true;
            }
            catch (Exception objE)
            {
                
            }
        }
        else
        {
            return true;
        }
    }
 
Share this answer
 
v2

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