C# 将带参数的 SqlCommand 转换为 DataTable
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13870843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Turning a SqlCommand with parameters into a DataTable
提问by cdub
I'm adapting some code that someone else wrote and need to return a DataTable for time's sake.
我正在改编一些其他人编写的代码,为了时间的缘故需要返回一个 DataTable。
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?
但是返回数据表的最佳方法是什么?
采纳答案by Thomas C. G. de Vilhena
Use the DataTable.Loadmethod to fill your table with values from the SqlDataReader:
使用DataTable.Load方法用来自 SqlDataReader 的值填充您的表:
using (SqlDataReader dr = command.ExecuteReader())
{
var tb = new DataTable();
tb.Load(dr);
return tb;
}
回答by dmaij
By using a DBDataAdapter
通过使用 DBDataAdapter
excerpt from ms documentation
摘自 ms 文档
// Create the DbDataAdapter.
DbDataAdapter adapter = new DbDataAdapter();
adapter.SelectCommand = command;
// Fill the DataTable.
DataTable table = new DataTable();
adapter.Fill(table);

