将 SQL 数据读取器数据加载到 DataTable 时遇到问题
string query = "select * from cfo_daily_trans_hist";
try
{
using (SqlConnection connection = new SqlConnection(
cnnString))
{
SqlCommand command = new SqlCommand(query);
command.Connection = connection;
connection.Open();
var result = command.ExecuteReader();
DataTable datatable = new DataTable();
datatable.Load(result);
connection.Close();
}
}
因此,var result
是通过ExecuteReader();
创建的,并且HasRows
是true
,并且它显示了正确的结果字段数量。但是,我从中创建的 DataTable 是空的。
我做错了什么?我 99% 确定它正在获取数据,但我不知道如何通过 SqlDataReader
对象找到它来确定。
谢谢。
string query = "select * from cfo_daily_trans_hist";
try
{
using (SqlConnection connection = new SqlConnection(
cnnString))
{
SqlCommand command = new SqlCommand(query);
command.Connection = connection;
connection.Open();
var result = command.ExecuteReader();
DataTable datatable = new DataTable();
datatable.Load(result);
connection.Close();
}
}
So the var result
is created through the ExecuteReader();
and HasRows
is true
, and it shows the correct amount of fields. However, the DataTable
that I create from it is empty.
What am I doing wrong? I'm 99% sure it's getting data, but I don't know how to find it through the SqlDataReader
object to make sure.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
SqlDataAdapter
而不是SqlDataReader
。使用
SqlDataAdapter
,您无需显式调用SqlConnection.Open()
和SqlConnection.Close()
。它在Fill()
方法中处理。Instead of a
SqlDataReader
, use aSqlDataAdapter
.With a
SqlDataAdapter
, you don't need to explicitly callSqlConnection.Open()
andSqlConnection.Close()
. It is handled in theFill()
method.您可以尝试在sql命令语句中添加“COALESCE”...如果查询结果中有一些NULL值,则数据表将会出现问题
You can try to add "COALESCE" in your sql command statement ... if you have some NULL value in your query result, you will have problem with dataTable