0

What is the proper way of closing a tread after running a query against a MySql database from a windows form in C#?

Is a simple open close enough like this?

conn.Open();

//querycode

conn.Close():
Harry Johnston
  • 35,639
  • 6
  • 68
  • 158
Darkmage
  • 1,583
  • 9
  • 24
  • 42
  • What do you mean by "close a tread"? Do you mean you want to make sure that the connection is closed after making a SQL call? – Mark Carpenter Oct 08 '09 at 18:27
  • the problem im getting is that when i use the tool iv created m somtimes getting the "Too many connections" error, my mysql database is set ut with max_connections 100. and when i run a simple conn.Close(); after each query it does not seem to close the connection to the db. it dont releases the MySql treads before i restart the SW. – Darkmage Oct 08 '09 at 18:35

4 Answers4

3

Try to use:

using(MySqlConnection conn = new MySqlConnection(connString))
{
    conn.Open();
} // conn is automatically closed and disposed at the end of the using block
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
0

Classes that use resources that you need to clean up afterwards usually implement the IDisposable interface. This means it provides a function called Dispose() that can be used to free resources.

For disposable objects, you can use the using statement:

using ( SomeDisposableClass c = new SomeDisposableClass() ) {

    // ... your code here

} // c.Dispose() automatically called here, freeing up resources

If the class is properly coded, it should free any resources -- be it a database connection, an opened file handle, etc -- in its Dispose() function.

This means that the MySQL probably disconnects from the database in Dispose(), so you probably don't need to explicitly call c.Close() -- but always check the documentation to be sure.

csl
  • 10,937
  • 5
  • 57
  • 89
0

it is okay the way you are doing it, you can also wrap connection object into using block like this:

using (var con = new MySqlConnection(/*connection string*/))
{
    con.Open();
    //do stuff
    // con.Close(); //don't need this it will be closed automatically* 
}

(*see)

Community
  • 1
  • 1
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
0

No, the code in your question is not good enough. If your query throws an exception you won't Close() it in a timely manner and it will be left hanging until the garbage collector notices it.

You need to enclose the object in a using block as shown by others or at a bare minimum encase it in a try/finally structure.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794