Forum guidelines
AuthorQuestion
execute a select count sql in c#
Posted on: 08 Dec 2008

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

 


AuthorReply
Re: execute a select count sql in c#
Posted on: 08 Dec 2008  

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.Odbc
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();

        // 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();

Ron
  • 0
  • 0
Re: execute a select count sql in c#
Posted on: 09 Dec 2008  
Try this. private void button2_Click(object sender, EventArgs e) { SqlConnection myConnectionAdd = null; DataSet myDataSetAdd = new DataSet(); myConnectionAdd = new SqlConnection("Data Source=YourSource Catalog=YourCatalog;Integrated Security=True"); string mySqlInsert = "SELECT count(*) FROM dbo.Customers"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = new SqlCommand(mySqlInsert, myConnectionAdd); mySqlDataAdapter.Fill(myDataSetAdd, "count(*)"); dataGridView1.DataSource = myDataSetAdd.Tables["count(*)"]; myConnectionAdd.Close(); }
Re: execute a select count sql in c#
Posted on: 09 Dec 2008  
this is more of an edit to Jeff's post.  Not really necessary to use a DataReader object if just returning one column.

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);
    
}
}

"ExecuteScalar()" returns the first column of the first record.  Since we are only return one column of one record, it is the perfect solution.

Also, since you didn't state with database you were using, we chose to use the ODBC connection.  If you are using SQL Server, you can use "SqlConnection" and "SqlCommand" instead.

Employers - Post Free Jobs

SPONSORED BY

Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.