mr_blond
mr_blond

Reputation: 1730

How can I find out if I need to call Close() in MySqlConnection when using?

using MySql.Data.MySqlClient;

The simple connection code with "using":

using (IDbConnection sql = new MySqlConnection(ConnectionString))
     {
           try
           {
                sql.Open();
                var x = sql.Execute("query...");
           }
            catch (Exception ex)
           {
                 Console.WriteLine(ex.Message);
           }
     }

"Using" calls Dispose(), but if Dispose() calls Close()?

How can I find out if I need to call Close() in MySqlConnection when using?

Upvotes: 0

Views: 926

Answers (3)

This is a sample DBConnect class that I am using. With this class, it is really easy to create a database connection anywhere you want. Just create an object of this class.

This is for MySQL database, if you are using sql server just replace MySql with Sql

Here is my DBConnect class

using System    ;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;


namespace test
{

    class DBConnect: IDisposable 
    {
        private static String server = "localhost";
        private static String port = "3306";
        private static String database = "testDB";
        private static String username = "root";
        private static String password = "";

        private static String connectionString = "Server=" + server + ";Port=" + port + ";Database=" + database + ";Uid=" + username + ";Password=" + password + ";";
         public MySqlConnection con = new MySqlConnection(connectionString);



        public DBConnect() //Constructor
        {

            try
            {
                con.Open();
                Console.WriteLine("Database connected");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                Console.WriteLine("Database Connection Failed");
                throw new Exception();
            }


        }


        public void Dispose()
        {
            con.Close();
        }
    }
}

Here is how you use this class

using(DBConnect db = new DBConnect())
{
    String q = "your sql Statement here";
    MySqlCommand cmd = new MySqlCommand(q, db.con);
    cmd.ExecuteNonQuery();
    MessageBox.Show("Item added", "Done", MessageBoxButtons.OK,mesageBoxIcon.Information);
                }

Upvotes: 0

Fabio
Fabio

Reputation: 32445

Do nothing.

Dispose will close connection properly.

From documentation:

Dispose() - Releases all resources used by the MySqlConnection

Form the source code of MySqlConnection.Dispose

void IDisposable.Dispose()
{
    if (State == ConnectionState.Open)
        Close();
}

Upvotes: 2

China Syndrome
China Syndrome

Reputation: 993

Here you can try this, u can put it in a finally clause

if (sql.State == ConnectionState.Open)
{
    sql.Close();
}

Upvotes: 0

Related Questions