Trouble loading SQL Data Reader data into DataTabl

2019-02-14 04:59发布

问题:

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.

回答1:

Instead of a SqlDataReader, use a SqlDataAdapter.

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

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