Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 753
  • 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
Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

 
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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