I'm using the library microsoft.practices.enterpriselibrary, to access a SQL Server database. I'm wondering how to close connection when I use the ExecuteNonQuery method?
ie:
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
SqlDatabase db = null;
try
{
db = new SqlDatabase(stringConnection);
db.ExecuteNonQuery("storedprocedure", someParams);
}
catch (Exception ex)
{
}
I can't do something like
finally
{
if (db != null)
{
((IDisposable)db).Dispose();
}
}
So... how can I avoid connection leaks?
Thank you.
You can put the code inside the "using" block. This will ensure the connection closed after finishing.
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
SqlDatabase db = new SqlDatabase(stringConnection);
using (DbConnection con = db.CreateConnection())
{
db.ExecuteNonQuery("storedprocedure", someParams);
}
or you can use the con.Close().
Generally you do not need to worry about closing the connection, as Data Access Block manages connections more efficiently. check "Managing Connections" section in below link: http://msdn.microsoft.com/en-us/library/ff953187(v=pandp.50).aspx
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