Link to home
Start Free TrialLog in
Avatar of bmanmike39
bmanmike39

asked on

How do I use the ExecuteScalar to count number of rows in my dB

Im trying to excite a scalar comment, to do a count of records but cant get it to work
I  dont know how to write the command.

Thanks for any help!

Code I have:

SqlConnection sqlConnection1 = new SqlConnection("Data Source=s...string works");
        SqlCommand cmd = new SqlCommand();
       
        //OpenFile connection
        sqlConnection1.Open();

        cmd.CommandType = CommandType.Text;
        cmd.Connection = sqlConnection1;
        myv = (int)cmd.ExecuteScalar();
        // close connection
        sqlConnection1.Close();
ASKER CERTIFIED SOLUTION
Avatar of prairiedog
prairiedog
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bmanmike39
bmanmike39

ASKER

It works but it returns 8 rows when i only have 7 records
Do you have duplicate records in DB?
no counted them just 7
Try this:
SELECT DISTINCT COUNT(*) FROM myTable
run the commandtext query from your commamd object in the database and then check the results
actually they should match
sorry i was looking at the wrong table.  thanks it works