Gabbyboy Gabbyboy - 4 months ago 84
C# Question

How to close connection of Microsoft.Practices.EnterpriseLibrary.Data.ExecuteNonQuery

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.

Answer

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().