Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 455
Gabbyboy Avatar asked Dec 07 '22 08:12

Gabbyboy


2 Answers

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

like image 141
Tony Li Avatar answered Jan 22 '23 20:01

Tony Li


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

like image 29
Tushar Kesare Avatar answered Jan 22 '23 21:01

Tushar Kesare