【问题标题】:Reusable code to retrieve data可重用代码来检索数据
【发布时间】:2011-06-05 06:47:56
【问题描述】:

我找到了一个非常好的方法,只需指定存储过程名称就可以从数据库中检索任何结果集。我认为代码是非常可重用的。代码如下

using System.Data;
using System.Data.SqlClient;

private DataSet GetFreshData(string sprocName)
{
    using ( SqlConnection conn = new SqlConnection() )
    {
        using ( SqlDataAdapter da = new SqlDataAdapter() )
        {        
            da.SelectCommand = new SqlCommand();
            da.SelectCommand.CommandText = sprocName;
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Connection = conn;

            DataSet ds = new DataSet();

            try
            {
                da.SelectCommand.Connection.Open();
                da.Fill(ds);
                da.SelectCommand.Connection.Close();
            }
            catch
            {
                return null;
            }
            finally
            {
                // do other things...calling Close() or Dispose() 
                // for SqlConnection or SqlDataAdapter objects not necessary
                // as its taken care of in the nested "using" statements
            }

            return ds;
        }
    }
} 

我的问题是当存储过程需要指定几个参数时,有人可以建议修改这个方法

【问题讨论】:

  • 我建议也捕获存储过程的输出,将其放入一个可以同时保存输出和数据集的对象中(以防出现任何错误)
  • 是的,代码是可重用的,但是当存储过程返回一个值(例如聚合函数的结果)时,这可能是矫枉过正。所以也有一个GetScalarData或类似的功能,做一个SqlCommand.ExecuteScalar。还要执行一个不返回任何值的 SP,有一个 ExecuteSP 函数将执行一个 SqlCommand.ExecuteNonQuery
  • 恭喜!!你重新发明了轮子

标签: asp.net database code-reuse


【解决方案1】:

简单! :) 将SqlParameter[] 作为函数的第二个参数。

然后确保da.SelectCommand.ParametersSqlParameter[] 中的SqlParameter 对象列表填充

【讨论】:

  • 是的,这是最简单的,不是吗?您甚至可以将其设为默认为零参数的新数组
猜你喜欢
  • 1970-01-01
  • 2021-09-22
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多