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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Satish BhatPosted Oct 1, 2011, 3:26 AM
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 RajaPosted Oct 1, 2011, 5:27 AM