Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 756
  • Last Modified:

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();
0
bmanmike39
Asked:
bmanmike39
  • 3
  • 3
  • 2
2 Solutions
 
prairiedogCommented:
your select query:
SELECT COUNT(*) FROM myTable
0
 
Anurag ThakurTechnical ManagerCommented:
try this

        cmd.CommandType = CommandType.Text;
        cmd.Connection = sqlConnection1;
        cmd.CommandText = "SELECT COUNT(*) FROM myTable";
        myv = (int)cmd.ExecuteScalar();
        // close connection
        sqlConnection1.Close();
0
 
bmanmike39Author Commented:
It works but it returns 8 rows when i only have 7 records
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
prairiedogCommented:
Do you have duplicate records in DB?
0
 
bmanmike39Author Commented:
no counted them just 7
0
 
prairiedogCommented:
Try this:
SELECT DISTINCT COUNT(*) FROM myTable
0
 
Anurag ThakurTechnical ManagerCommented:
run the commandtext query from your commamd object in the database and then check the results
actually they should match
0
 
bmanmike39Author Commented:
sorry i was looking at the wrong table.  thanks it works
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 3
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now