Hi frnds,
i want to know which are the connection to be closed in finally block in asp.net web form..how it can be done..pls explain
thanks
@@mir
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Satish BhatRank #2,496 · 563 reputationPosted Sep 30, 2011, 11:26 PM EDT
Here is the sample code
SqlConnection connection = new SqlConnection(connectionString);
try
{
string queryString = "YOUR ACTUAL QUERY"
using (SqlCommand command = new SqlCommand(queryString, connection))
{
command.Connection.Open(); // Open connection
command.ExecuteNonQuery(); // Execute query
}
}
catch (Exception e)
{
// Handle, re-throw. Also, you might want to catch more specific exceptions.
}
finally
{
if (connection != null)
You can also use 'using' statement around the code that uses the connection.
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM SomeTable"; //Or any command like Insert/Update/Delete
// Execute the query here...
} // Connection automatically closed
When the end of the using statement block is reached, connection object gets disposed immediately.
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way. It also causes the object itself to go out of scope as soon as Dispose is called
Prabhu RajaRank #861 · 2.6K reputationPosted Oct 1, 2011, 1:27 AM EDT