最近我发现自己编写数据访问层选择方法,其中代码都采用这种通用形式:
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集合)?