[英]How to pass stored procedure name as parameter in DAL
I have more than one function which simply fetches data from DB. 我有多个功能,可以简单地从数据库中获取数据。 The difference among the function is the stored procedure name (uspLoadStudents,uspLoadMarks)
. 函数之间的区别是存储过程名称(uspLoadStudents,uspLoadMarks)
。 To optimize, make it as one function and passes the SP. 要进行优化,请将其作为一个功能并通过SP。
public DataSet LoadSubjects()
{
string SqlDBConnection = Utils.GetConnectionString();
DataSet ds = new DataSet();
SqlConnection sqlConn = new SqlConnection(SqlDBConnection);
SqlCommand sqlCmd = new SqlCommand("uspLoadSubjects", sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(sqlCmd.ExecuteReader());
ds.Tables.Add(dt);
sqlConn.Close();
return ds;
}
This? 这个?
public DataSet ExecProc(string procName)
{
string SqlDBConnection = Utils.GetConnectionString();
DataSet ds = new DataSet();
SqlConnection sqlConn = new SqlConnection(SqlDBConnection);
SqlCommand sqlCmd = new SqlCommand(procName, sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(sqlCmd.ExecuteReader());
ds.Tables.Add(dt);
sqlConn.Close();
return ds;
}
try this 尝试这个
public static DataSet getDataSet(string sp_name, string[] param_names, object[] param_values)
{
SqlDataAdapter sqlda = new SqlDataAdapter();
SqlCommand sqlcmd = new SqlCommand();
DataSet set = new DataSet();
try
{
sqlcmd.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = sp_name;
sqlda.SelectCommand = sqlcmd;
sqlda.Fill(set);
}
catch (Exception ex)
{
}
finally
{
if (sqlcmd.Connection.State == ConnectionState.Open)
sqlcmd.Connection.Close();
}
return set;
}
Information like sql command, stored procedure name, should be part of your Data Access Layer
, instead it is a helper class inside the data access layer. 诸如sql命令,存储过程名称之类的信息应成为Data Access Layer
,而应是Data Access Layer
内的帮助类 。 Try this: 尝试这个:
public static class DALHelper
{
public static DataSet ExecuteProcedure(string procedureName)
{
string sqlDBConnection = Utils.GetConnectionString();
DataSet ds = new DataSet();
using (SqlConnection sqlConn = new SqlConnection(sqlDBConnection))
{
using(SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConn))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
try
{
sqlConn.Open();
using (var adapter = new SqlDataAdpter(sqlCmd))
{
adapter.Fill(ds);
}
}
catch
{
throw;
}
finally
{
sqlConn.Close();
}
}
}
return ds;
}
}
Implement a method to use this helper, for sample: 实现一个使用此助手的方法,例如:
public DataSet LoadSubjects()
{
return DALHelper.ExecuteProcedure("uspLoadStudents");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.