无法加载SQL数据读取数据到数据表 [英] Trouble loading SQL Data Reader data into DataTable

查看:159
本文介绍了无法加载SQL数据读取数据到数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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结果通过的ExecuteReader()创建的; HasRows ,它显示领域的正确的金额。但是,数据表,我从它创建为空。

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.

感谢。

推荐答案

而不是一个 SqlDataReader的,使用的SqlDataAdapter

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

随着的SqlDataAdapter ,你并不需要显式调用在SQLConnection.open()在SQLConnection.close()。它在处理的填写()方法。

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

这篇关于无法加载SQL数据读取数据到数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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