I made a class for DB connection like this:
public class DbHelper : IDisposable
{
private bool disposed;
public DbHelper()
{
disposed = false;
}
public static SqlConnection ConnectionSender()
{
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbname"].ConnectionString);
return conn;
}
public System.Int32 ExecuteNonQuerySender(SqlCommand cmd)
{
System.Int32 result;
using (var conn = ConnectionSender())
{
conn.Open();
cmd.Connection = conn;
result = cmd.ExecuteNonQuery();
}
return result;
}
~DbHelper()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
}
}
disposed = true;
}
}
I call this class using method:
var cmdParent = new SqlCommand { CommandText = sqlQuery };
using (var helper = new DbHelper())
{
dt = helper.ExecuteNonQuerySender(cmdParent);
}
This works fine but my server is overloaded and I suspect about DB leaking. DB connection objects should be closed and disposed in this code. Did I do something wrong? (programmatically)
I know there are also professional ways to solve DB connection but i want to try this code.
First off, it looks like you didn’t give us the whole DbHelper class. You don’t show the
DataTableSendermethod, but you use it in your example.Secondly, assuming that there isn’t anything unexpected in the rest of DBHelper, nothing in this class needs any of the dispose logic. You can remove the
IDisposableimplementation entirely, along with the finalizer, the Dispose method, and thedisposedvariable, and it will make no difference (other than allowing you to remove the using clauses when using the class). I’d recommend doing that and making the class a static class (requires making the ExecuteNonQuerySender method static also).Finally, there is nothing here which is leaking connections, however callers could be ‘leaking’ connections if they call
ConnectionSenderand never close/dispose the connection that they get back.