2011-06-05 35 views
0

我发现了一个很不错的方法来检索任何结果只是通过指定存储过程name.i认为代码数据库中设置的数据非常多reusable.code是如下可重用代码来检索

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; 
     } 
    } 
} 

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

+0

我建议捕获存储过程的输出也一样,它放入一个对象,可容纳两个输出和数据集的列表( case有任何错误) – 2011-06-05 06:52:32

+0

是的代码是可重用的,但是当存储过程返回一个值(例如聚合函数的结果)时,这可能是矫枉过正的。所以也有一个'GetScalarData'或类似的函数,并执行'SqlCommand.ExecuteScalar'。还要执行一个不返回任何值的SP,有一个'ExecuteSP'函数,它将执行'SqlCommand.ExecuteNonQuery'。 – 2011-06-05 06:57:39

+2

祝贺你!你已经改造了轮子 – Eranga 2011-06-05 06:59:04

回答

3

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

然后确保da.SelectCommand.Parameters充满SqlParameter对象在SqlParameter[]

+0

是最简单的,不是吗?你甚至可以使它默认为一个带有零参数的新数组 – 2011-06-05 06:51:20