简体   繁体   中英

DataTable Row count always returning 1

I am trying to get the total number of rows of a table using a data adapter but my row count always returns 1. When i use the reader, I get the accurate number. I would like to use a dataAdapter.

Here is my code:

public double GetRowNumber()
    {
        using (OleDbConnection con = new OleDbConnection(someConnectionString))
        {
            con.Open();
       String cmdString = "SELECT COUNT (*) FROM " + "[" + Table +"]" 

            OleDbDataAdapter db = new OleDbDataAdapter(cmdString, dbConn);
            DataTable dt = new DataTable();
            db.Fill(dt);
            return dt.Rows.Count;

        }
    }

Any ideas?

Your function will always return 1 because

SELECT COUNT (*) FROM " 

statement will fill your datatable with 1 record, the number of count.

If you want the row count use

   con.Open();
   String cmdString = "SELECT COUNT (*) FROM " + "[" + Table +"]" 
   OleDbCommand cmd = new OleDbCommand();
   cmd.Text = cmdString ;
   cmd.Connection = con;
   int count = Convert.ToInt32(cmd.ExecuteScalar());

more quick and light for what you want. You do not have to use an object such datatable.

Because your query is returning only one row. If you run sql server manager and execue your query.

The result will be like this.

在此输入图像描述

The table does have only one row. It contains a single cell, with the amount of rows in the database for the table in the query. That is, the result of your query is a one row, one column set.

Instead of dt.Rows.Count, you could return dt.Rows[0][0]; , but that's overkill. But in a case like this, I think using ExecuteScalar() is the best practice (ninja'ed from kostas so kudos and upvotes to him).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM