最近我发现自己正在编写数据访问层选择方法,其中代码都采用这种一般形式:
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;
}
或者像这样:
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;
}
这些方法将由业务层代码调用,然后将基本 DataTable 或 DataRecord 转换为表示层可以使用的强类型业务对象。
由于我反复使用类似的代码,我想确保这个代码是最好的。那么如何改进呢?而且,是否值得尝试将通用代码从这里移到它自己的方法中。如果是这样,该方法会是什么样子(特别是关于传入 SqlParameter 集合)?