Home > front end >  What's better: to open connection in every method or one time in constructor?
What's better: to open connection in every method or one time in constructor?

Time:07-10

Is it normally to create an instance "connection" (type of MySqlConnection) every time in every methods in form (I have about 20 methods) and open connection with Open method (in the start of the method) and close connection with Close method (in the end of the method)?

Code (one of my methods):

private void buttonOk_Click(object sender, EventArgs e)
        {
            
            MySqlConnection conn = new MySqlConnection(connStr);
            conn.Open();
            // other code
            conn.Close(); 
        }

Or in my case it is better to create a field inside form class and open connection in constructor and close connection in the form_closed method or in destructor?

CodePudding user response:

depends on the implementation of the SqlConnection and the configuration.

In your case (the MySqlConnection) and in most variants of other databases, there is a pooling implementation under the hood.

https://dev.mysql.com/doc/connector-net/en/connector-net-connections-pooling.html

If there is pooling, there is no benefit of keeping a connection open without using it. If there is a poolsize of 1000 Connections, you can only instanz 1000 of your classes, the next one needs to wait, untill one of the other connection will be closed.

So, its better to open a connection directly, where you need it and as long you need it to not dry out the pool.

And don't forget to dispose the connection

Another reason could be mutlithreading -> connections are not threadsafe. Avoiding a shared connection will avoid threading issues

  • Related