我有多个函数只能从DB中获取数据。函数之间的区别在于存储过程名称[[UIApplication sharedApplication] statusBarFrame]
。要进行优化,请将其作为一个函数并通过SP。
(uspLoadStudents,uspLoadMarks)
答案 0 :(得分:0)
此?
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;
}
答案 1 :(得分:0)
试试这个
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;
}
答案 2 :(得分:0)
sql命令,存储过程名称等信息应该是Data Access Layer
的一部分,而不是数据访问层内的helper class。试试这个:
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;
}
}
为示例实现一个使用此帮助程序的方法:
public DataSet LoadSubjects()
{
return DALHelper.ExecuteProcedure("uspLoadStudents");
}