急,,,,,存储过程
如何把类似于这种的存储过程抽取一个公用的方法,请教下
/// <returns>年级集合</returns>
public IList<Grade> GetAllGrades()
{
IList<Grade> Grades = new List<Grade>();
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand objCommand = new SqlCommand(dboOwner + ".usp_SelectGradesAll", conn);
objCommand.CommandType = CommandType.StoredProcedure;
conn.Open();
using (SqlDataReader objReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection))
{
while (objReader.Read())
{
Grade grade = new Grade();
grade.Name = Convert.ToString(objReader["GradeName"]);
Grades.Add(grade);
}
objReader.Close();
objReader.Dispose();
}
conn.Close();
conn.Dispose();
}
return Grades;
}
/// <summary>
/// 通过年级名称得到年级ID
/// </summary>
/// <param name="gradeName">年级名称</param>
/// <returns>年级ID</returns>
public int GetGradeIDByGradeName(string gradeName)
{
int number = 0;
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand objCommand = new SqlCommand(dboOwner + ".usp_SelectGradeIDByGradeName", conn);
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.Parameters.Add("@GradeName", SqlDbType.NVarChar, 50).Value = gradeName;
conn.Open();
using (SqlDataReader objReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection))
{
if (objReader.Read())
number = Convert.ToInt32(objReader["GradeID"]);
objReader.Close();
objReader.Dispose();
}
conn.Close();
conn.Dispose();
}
return number;
}
#endregion
}
--------------------编程问答-------------------- 这是数据层呀
你想变成什么模样的?
--------------------编程问答-------------------- 提出一个公共的方法,这样不是写许多重复的代码吗
--------------------编程问答-------------------- 看看sqlhelper
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = cmd;
da.Fill(ds);
return ds;
}
catch
{
conn.Close();
throw;
}
}
--------------------编程问答-------------------- 对数据库访问公共的部分提取出来
对个性的东西用参数表示 --------------------编程问答-------------------- 把重复的部分提取在静态方法内 --------------------编程问答-------------------- 存储过程使用很方便的 sqlcommand("exec pro_ccgc") --------------------编程问答-------------------- 自己重构一下代码,也是一种学习,为何不自己试试呢?
补充:.NET技术 , C#