Lately I find myself writing data access layer select methods where the code all takes this general form:
public static DataTable GetSomeData( ... arguments)
{
string sql = " ... sql string here: often it's just a stored procedure name ... ";
DataTable result = new DataTable();
// GetOpenConnection() is a private method in the class:
// it manages the connection string and returns an open and ready connection
using (SqlConnection cn = GetOpenConnection())
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
// could be any number of parameters, each with a different type
cmd.Parameters.Add("@Param1", SqlDbType.VarChar, 50).Value = param1; //argument passed to function
using (SqlDataReader rdr = cmd.ExecuteReader())
{
result.Load(rdr);
}
}
return result;
}
Or like this:
public static DataRow GetSomeSingleRecord( ... arguments)
{
string sql = " ... sql string here: often it's just a stored procedure name ... ";
DataTable dt = new DataTable();
// GetOpenConnection() is a private method in the class:
// it manages the connection string and returns an open and ready connection
using (SqlConnection cn = GetOpenConnection())
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
// could be any number of parameters, each with a different type
cmd.Parameters.Add("@Param1", SqlDbType.VarChar, 50).Value = param1; //argument passed to function
using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
dt.Load(rdr);
}
}
if (dt.Rows.Count > 0)
return dt.Rows[0];
return null;
}
These methods would be called by business layer code that then converts the base DataTable or DataRecord into strongly typed business objects that the presentation tier can use.
Since I'm using similar code repeatedly, I want to make sure this code is the best it can be. So how can it be improved? And, is it worth trying to move the common code from this out to it's own method. If so, what would that method look like (specifically with regards to passing an SqlParameter collection in)?
See Question&Answers more detail:os