I am trying to execute a simple sql select statement using C# and I want to return the number of rows. What is the correct syntax.
SELECT Count(*) FROM InvData
I am trying to execute a simple sql select statement using C# and I want to return the number of rows. What is the correct syntax.
SELECT Count(*) FROM InvData
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
cmd.CommandText = "SELECT COUNT(*) FROM InvData";
Int32 count = (Int32) cmd.ExecuteScalar();
above code helps you to make it working.
public static void ReadData(string connectionString)
{
string queryString = "SELECT count(*) from INV";
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
OdbcCommand command = new OdbcCommand(queryString, connection);
connection.Open();
int count = command.ExecuteScalar();
Console.WriteLine("Count is: {0}", count);
}
}
Try the snippet below, you may need to research some of the other classes to get your connectionString (DSN= etc), but this worked for me.
using System.Data.Odbcpublic static void ReadData(string connectionString) { string queryString = "SELECT count(*) from INV"; using (OdbcConnection connection = new OdbcConnection(connectionString)) { OdbcCommand command = new OdbcCommand(queryString, connection); connection.Open(); // Execute the DataReader and access the data. OdbcDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine("CustomerID={0", reader[0]); // Call Close when done reading. reader.Close();
Rijwan AnsariPosted Nov 12, 2021, 3:02 PM
geetha velusamyPosted Nov 12, 2021, 1:47 PM
Jignesh KumarPosted Nov 2, 2021, 2:06 AM
Vinitha TPosted Nov 1, 2021, 12:33 PM
public static int Count(string connectionString)
{
string query = "Select Count(*) From InvData";
int count="";
using (SqlConnection con = new SqlConnection(Your data source ConnectionString))
{?SqlCommand cmd = new SqlCommand(query, con);?cmd.CommandType = CommandType.Text;?con.Open();?count = cmd.ExecuteScalar();?}
return count;?}
Here, Using statement is used so no need to close the connection, it will close automatically.
ExecuteScalar is used to retrieve single value from database, so for counting the data ExecuteScalar can be used.
Ananth GPosted Nov 3, 2016, 7:51 AM