无法加载SQL数据读取数据到数据表数据、数据表、加载、SQL

2023-09-04 01:20:04 作者:痞

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.

 
精彩推荐