Hi guys,
In C# when i use the using statement. in case of try catch do i have to close the connection in case of any error.

try
    {
     using (connect=connecttodabase())
        {
        SqlParameter demo_ID = new SqlParameter();
        SqlCommand command = new SqlCommand("Demo", connect);
        command.Parameters.Add(demo_ID);
        int rowsAffected = command.ExecuteNonQuery();
        return demo_ID.Value.ToString();
        }
    }
catch (Exception)
    {
     throw;
    }

Do i have to close the connection using finally.

Recommended Answers

All 6 Replies

Hi,
your code looks pretty strange, especially the using(xxx) row, but I dont know what those variables mean, so hard to tell...
Lets make it a bit different:

private void DeletingDataBase()
        {
            using (SqlConnection sqlConn = new SqlConnection("ConnectionString"))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    string sqlQuery = "SELECT, INSERT, UPDATE, DELETE";
                    cmd.Connection = sqlConn;
                    cmd.CommandText = sqlQuery;
                    cmd.Connection.Open();
                    try
                    {                        
                        cmd.ExecuteNonQuery();
                    }
                    catch { /*catch an error in here*/ }
                    finally
                    {
                        cmd.Connection.Close();
                    }
                }
            }
        }

Back to your question. Answer is: No.
When you use a keyword "using" the newly created instance in there, closes it self when leaving the using brackets.
This is the same of every instance created (i.e: SqlConnection, StreamReader ...).
But if some einstance needs an open connection, you have to open it (manully) in the code (i.e: sqlConn.Open();).

using(SqlConnection sqlConn = new SqlConnection("string"))
{
    //open the connect (if needed)!
}//here the connection closes it self!

Hope it helps,
Mitja

hey Thanks for your answer!!:)

Just FYI, having

using (Type variable = something that implements IDisposable) {
    // code here
}

Is translated by the compiler into

Type variable = something that implements IDisposable;
try {
   // code here
} finally {
    if (variable.Disposed == false) {
        variable.Dispose();
    }
}

@Mitja Bonca, Thanks for you help.
@Momerath
I have a method getconnection which returns and open database connection.
and in my method i am using "using statement" do i have to close in case of error.

what my question is that do i have to close the connection in InsertInto() if the function catches and error.

internal static SqlConnection connecttodabase()
        {
            try
            {
                connectionString =ConfigurationManager.ConnectionStrings["Coonectionstring."].ConnectionString;

                SqlConnection connection = new SqlConnection(connectionString);
                    connection.Open();
                
                    return connection;
                
            }
catch()
{

}
}



  protected  static string InsertInto()
        {
            SqlConnection connect;
           
            
            try
                {
                    using (connect = connecttodabase())
                     {
 catch (Exception ee)
                {
                                     
                    
                    throw;
                }

If you are talking about the code from lines 21-35 then no, the finally clause will execute even if you throw an exception. Dispose() will be called as soon as you leave the using {} block of code, no matter how you leave (block ends, return, exception, etc.)

@Momerath Thanks for your help:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.