I use a pattern that looks something like this often. I'm wondering if this is alright or if there is a best practice that I am not applying here.
Specifically I'm wondering; in the case that an exception is thrown is the code that I have in the finally block enough to ensure that the connection is closed appropriately?
public class SomeDataClass : IDisposable
{
private SqlConnection _conn;
//constructors and methods
private DoSomethingWithTheSqlConnection()
{
//some code excluded for brevity
try
{
using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection))
{
_SqlConnection.Open();
countOfSomething = Convert.ToInt32(cmd.ExecuteScalar());
}
}
finally
{
//is this the best way?
if (_SqlConnection.State == ConnectionState.Closed)
_SqlConnection.Close();
}
//some code excluded for brevity
}
public Dispose()
{
_conn.Dispose();
}
}
You must explicitly close the connection by calling Close or Dispose." In your first example you do not "explicitly close the connection". When using the using statement, it calls Dispose method on the object being used, which in turn would call Close method, in case of SqlCeConnection .
SQLException: Invalid state, the Connection object is closed.
If connection pooling is off, the transaction is rolled back after SqlConnection. Close is called. Transactions started through System. Transactions are controlled through the System.
If you do not close your database connections, many problems can occur like web pages hanging, slow page loads, and more. Think of it as going through a door to your house. Maybe the door will shut by itself, but maybe it won't. If it doesn't shut, who knows what will happen.
Wrap your database handling code inside a "using"
using (SqlConnection conn = new SqlConnection (...))
{
// Whatever happens in here, the connection is
// disposed of (closed) at the end.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With