Thursday, February 16, 2012

Best way to pervent unused and left open connection to sql

Hello every one i had a design question.

What would be the best way to approach a problem such as a perventing unsed and left open sql connections

i have written a class called DataBase Manger but my question is should this class be static or none-static. right now the way i have is something like this

private SqlConnection Get() {
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["StringConnetionName"].ConnectionString);
sqlCon.Open();
return sqlCon;
}

/// <summary>
/// Closes a connection to the Database
/// </summary>
/// <param name="sqlCon"> Database connection to close</param>
private void Let(SqlConnection sqlCon) {
sqlCon.Close();
sqlCon = null;
}

then for example to run a store proc i have


public int RunProc(string procName,params SqlParameter[] p) { SqlConnection con = Get();try {using (SqlCommand cmd = CreateCommand(con, procName, p)) { cmd.ExecuteNonQuery();return (int)cmd.Parameters["ReturnValue"].Value; } }finally { Let(con); } }

now every time in any class or method i need to create a new Database manager and call the run proc object. Would it be a better desing to make this class static? so it would be just

DataBaseManger.RunProc(blah,blah)

or is it a better OO design to have it the way i have it. is is more secure in a webapplication? can these connections be hijacked?

thanks in adanvce, any help would greatly be apperiated. or any link to any related tutorials

thanks,

Amir

if you consider the design of the old MS Data Access Application Block (SqlHelper), you will see that virtually all the methods are static methods.

This is a very convenient approach and works well.

Rather than reinvent the wheel, why not look at incorporating the new data access application block from the enterprise library?

No comments:

Post a Comment