Turning a SqlCommand with parameters into a DataTable

徘徊边缘 提交于 2019-12-17 18:11:49

问题


I'm adapting some code that someone else wrote and need to return a DataTable for time's sake.

I have code like this:

using (SqlCommand command = new SqlCommand(query, conn))
{
      //add parameters and their values

      using (SqlDataReader dr = command.ExecuteReader())
      {
          return dr;
      }

But what's the best way to return a datatable?


回答1:


Use the DataTable.Load method to fill your table with values from the SqlDataReader:

using (SqlDataReader dr = command.ExecuteReader())
{
    var tb = new DataTable();
    tb.Load(dr);
    return tb;
}



回答2:


By using a DBDataAdapter

excerpt from ms documentation

// Create the DbDataAdapter.
DbDataAdapter adapter = new DbDataAdapter();
adapter.SelectCommand = command;

// Fill the DataTable.
DataTable table = new DataTable();
adapter.Fill(table);


来源:https://stackoverflow.com/questions/13870843/turning-a-sqlcommand-with-parameters-into-a-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!