简体   繁体   中英

App not closing MySql connection properly

I'm having a serious issue with my app. It builds a lot of MySql connections and then it's causing a crash.

I build every method like that:

MySqlConnection connect = new MySqlConnection(
        local_connection_string
        ); //this is global variable.

    protected void sample()
    {
        try
        {
            connect.Open();
            MySqlCommand query = new MySqlCommand(
                "here some mysql command"
                , connect);
            query.ExecuteNonQuery();
        }
        catch
        {

        }
        finally
        {
            connect.Dispose();
            connect.Close();
        }
    }

For some reason it's not closing any of these connections and when I keep refreshing it builds connections on the server, once limit is hit app is crashing. All connections are closed when app is shut down.

try this:

using(MySqlConnection conn = new MySqlConnetion(local_connection_string)
{
    conn.open();
    MySqlCommand query = new MySqlCommand(
                "here some mysql command"
                , connect);
            query.ExecuteNonQuery();

}

using(resource){}: right way for IDisposable resource usage probably need to add: Application.ApplicationExit event with MySqlConnection.ClearAllPools()

To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.

using (MySqlConnection connection = new MySqlConnection(connectionString))
{
    connection.Open();
    // Do work here; connection closed on following line.
}

MySQL counter part uses Connection pooling and does not close when you call close instead it puts it in the connection pool!

Make sure you First Close then Dispose the Reader, Command, and Connection object!

You can use ConnectionString Parameter "Pooling=false" or the static methods MySqlConnection.ClearPool(connection) and MySqlConnection.ClearAllPools()

and Using keyword is the right way to go with this kind of Scenario.

Just close first the connection , before calling the dispose...

        finally
        {
            connect.Close();
            connect.Dispose();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM