How to get record count from OledbDataReader?
-
I have get some records by OleDbDataReader like this, OledbDataReader reader=cmd.ExecuteReader(); How to get the amount of records from it? Thanks!
rushing wrote:
How to get the amount of records from it?
Read all the records from it counting them as you go. There is no other way with a DataReader. But, you do have the option of of getting the database to tell you in advance (assuming you need to know in advance) by sending off a query to find out how many rows it expects to return. You can do this in the same command as your main data, or you can use a separate command. If it is the former you can do something like this:
OleDbCommand cmd = new SqlCommand();
cmd.Connection = myConnection;
cmd.CommandText = "SELECT COUNT(*) FROM MyTable; SELECT * FROM MyTable";
OleDbDataReader reader = cmd.ExecuteReader();
reader.Read(); // Reads the next row
int numRows = reader.GetInt();
reader.NextResult(); // Moves to the next result set in the reader
while(reader.Read()) // Reads the next row, returns false if there isn't another row
{
// Do stuff.
}Or you can use a separate command object requesting the count of the rows and use
ExecuteScalar()
on it. Does this help? ColinMackay.net "Man who stand on hill with mouth open will wait long time for roast duck to drop in." -- Confucius "If a man empties his purse into his head, no man can take it away from him, for an investment in knowledge pays the best interest." -- Joseph E. O'Donnell -
rushing wrote:
How to get the amount of records from it?
Read all the records from it counting them as you go. There is no other way with a DataReader. But, you do have the option of of getting the database to tell you in advance (assuming you need to know in advance) by sending off a query to find out how many rows it expects to return. You can do this in the same command as your main data, or you can use a separate command. If it is the former you can do something like this:
OleDbCommand cmd = new SqlCommand();
cmd.Connection = myConnection;
cmd.CommandText = "SELECT COUNT(*) FROM MyTable; SELECT * FROM MyTable";
OleDbDataReader reader = cmd.ExecuteReader();
reader.Read(); // Reads the next row
int numRows = reader.GetInt();
reader.NextResult(); // Moves to the next result set in the reader
while(reader.Read()) // Reads the next row, returns false if there isn't another row
{
// Do stuff.
}Or you can use a separate command object requesting the count of the rows and use
ExecuteScalar()
on it. Does this help? ColinMackay.net "Man who stand on hill with mouth open will wait long time for roast duck to drop in." -- Confucius "If a man empties his purse into his head, no man can take it away from him, for an investment in knowledge pays the best interest." -- Joseph E. O'Donnell