Search code examples
c#sqldatareader

Get a value of aggregate function count() from datareader


Coding in C# and My query is,

query = "select COUNT(*) as rowsCount from employee_leaves where PARTY_ID ='10'";

After executing,

OracleDataReader dr = command.ExecuteReader();

How can I now get the count into the int

the table I get from the database has 1 row containing 3 as,

I have tried this, int i = dr["rowsCount"];

and this, int i = dr.GetInt32(0);

but didn't work out.


Solution

  • Since you only need to get one value, use ExecuteScalar(). Example

    string sqlQuery = "select COUNT(*) as rowsCount from employee_leaves where PARTY_ID ='10'";
    OracleCommand command = new OracleCommand(sqlQuery, connection);
    // other codes here such as opening the connection
    int count = Convert.ToInt32(command.ExecuteScalar());