如何从存储过程中填充 DataTable

How to Populate a DataTable from a Stored Procedure(如何从存储过程中填充 DataTable)
本文介绍了如何从存储过程中填充 DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何从存储中检索表数据表的过程

我正在尝试填充我的数据表.我创建了一个数据表 tmpABCD,但我需要使用存储过程中的值填充它.我无法继续.

I am trying to populate my datatable. I have created a datatable tmpABCD but i need to populate this with the values from a stored procedure. I am not able to proceed further.

SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString);
sqlcon.Open();
SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon);

DataTable dt = new DataTable("tmpABCD");

dt.Columns.Add(new DataColumn("A"));
dt.Columns.Add(new DataColumn("B"));
dt.Columns.Add(new DataColumn("C"));
dt.Columns.Add(new DataColumn("D"));

推荐答案

您不需要手动添加列.只需使用 DataAdapter ,它很简单:

You don't need to add the columns manually. Just use a DataAdapter and it's simple as:

DataTable table = new DataTable();
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
using(var cmd = new SqlCommand("usp_GetABCD", con))
using(var da = new SqlDataAdapter(cmd))
{
   cmd.CommandType = CommandType.StoredProcedure;
   da.Fill(table);
}

请注意,您甚至不需要打开/关闭连接.这将由 DataAdapter 隐式完成.

Note that you even don't need to open/close the connection. That will be done implicitly by the DataAdapter.

与 SELECT 语句关联的连接对象必须是有效,但不需要打开.如果连接关闭在调用 Fill 之前,打开它以检索数据,然后关闭它.如果在调用 Fill 之前连接是打开的,它保持打开状态.

The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

这篇关于如何从存储过程中填充 DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)