In this article we will discuss, to close the connection using finally block .In .net exception is handled by using following keywords such as try, catch, finally and throw.
In ado.net connections should be opened as late as possible, and should be closed soon as possible. Closing the connection in the finally block for better performance and scalability.
Example:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Create the connection object
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ShoppingZone"].ConnectionString); ;
try
{
// Pass the connection to the command object, so the command object knows on which
// connection to execute the command
SqlCommand cmd = new SqlCommand("Select * from employee", connection);
// Open the connection. Otherwise you get a runtime error. An open connection is
// required to execute the command
connection.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
catch (Exception ex)
{
// Handle Exceptions, if any
}
finally
{
// The finally block is guarenteed to execute even if there is an exception.
// This ensures connections are always properly closed.
connection.Close();
}
}
}
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article