none
Exception :: "Too Many Connections" in c# window application RRS feed

  • Question

  • Hello,

     

    I have a class named as connection

     

     

    public class Connection

    {

    //This class is used to create connection with database. This class is

    //inhereted by all classes performing operations with database.

    protected MySqlConnection con;

     

    public static string ConnectionString;

     

    static Connection()

    {

    ConnectionString = "server=. ;uid= sa ; database = tempdatabase; pwd=;";

    }

     

    public Connection()

    {

    try

    {

    con = new MySqlConnection(ConnectionString);

    con.Open();

    }

    catch (Exception ex)

    {

    MessageBox.Show(ex.Message.ToString());

    Application.Exit();

    }

    }

     

    ~Connection()

    {

    if(con!=null)

    }

    }

     

    On events of form i am using the several objects of that class. On the end of that event procedure that object reference is set to null.

     

    After repeatedly doing that event I have encountered the error "Too many connections".

     

    Is it not enough to set the reference of object to null to close the connection. Or it require to explicitly to close the server connection before setting the reference of object of above mentioned class to null.

    Monday, October 1, 2007 11:26 AM

Answers

  • An addition to Zamial's reply. You need to close connection as soon as you finished working with data. You should not keep connection opened all the time during lifetime of the application. You also need to call Dispose method of the connection after it is closed using Close method.

    Monday, October 1, 2007 11:15 PM
    Moderator

All replies

  •  

    It's not enough, you should close the connection when you've finished.

     

    Otherwise the server wil maintain it until it decides to kill it due to inactivity. Which could be 30 minutes or never or 30 seconds.

    Monday, October 1, 2007 12:07 PM
  • An addition to Zamial's reply. You need to close connection as soon as you finished working with data. You should not keep connection opened all the time during lifetime of the application. You also need to call Dispose method of the connection after it is closed using Close method.

    Monday, October 1, 2007 11:15 PM
    Moderator
  • Thanx, I get the solution. But explain that why the disposing of connection is required after the connection is closed.

    Thursday, October 4, 2007 4:23 AM
  • Usually components or classes implement Dispose in a case when they use some unmanaged resources and they need to clean them up, since GC has no idea how to collect those resources. Basically Dispose cleans all the resources that cannot be collected by GC automatically.

    Thursday, October 4, 2007 10:31 AM
    Moderator