将 SQL Data Reader 数据加载到 DataTable 时遇到问题 [英] Trouble loading SQL Data Reader data into DataTable

查看:21
本文介绍了将 SQL Data Reader 数据加载到 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();创建的,HasRowstrue,它显示正确数量的字段.但是,我从中创建的 DataTable 是空的.

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.

我做错了什么?我 99% 确定它正在获取数据,但我不知道如何通过 SqlDataReader 对象找到它来确定.

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.

谢谢.

推荐答案

使用 SqlDataAdapter 代替 SqlDataReader.

SqlDataAdapter myAdapter = new SqlDataAdapter(command);
myAdapter.Fill(datatable);

使用SqlDataAdapter,您不需要显式调用SqlConnection.Open()SqlConnection.Close().它在 Fill() 方法中处理.

With a SqlDataAdapter, you don't need to explicitly call SqlConnection.Open() and SqlConnection.Close(). It is handled in the Fill() method.

这篇关于将 SQL Data Reader 数据加载到 DataTable 时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆