10

How to count the number of rows from sql table in c#? I need to extract some data from my database...

7 Answers 7

42

You may try like this:

select count(*) from tablename where columname = 'values'

C# code will be something like this:-

public int A()
{
   string stmt = "SELECT COUNT(*) FROM dbo.tablename";
   int count = 0;

   using(SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
   {
       using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
       {
           thisConnection.Open();
           count = (int)cmdCount.ExecuteScalar();
       }
   }
   return count;
}
Sign up to request clarification or add additional context in comments.

1 Comment

"Data Source=DATASOURCE" What should be the DATASOURCE here?
4

You need to make a database connection from c# first. Then, you need to pass below query as commandText.

Select count(*) from TableName

Use ExecuteScalar/ExecuteReader to get the returned count.

Comments

3

Do you means likes this ?

SELECT COUNT(*) 
FROM yourTable 
WHERE ....

Comments

3

You can make global function that you can use all the time as

    public static int GetTableCount(string tablename, string connStr = null)
    {
        string stmt = string.Format("SELECT COUNT(*) FROM {0}", tablename);
        if (String.IsNullOrEmpty(connStr))
            connStr = ConnectionString;
        int count = 0;
        try
        {

            using (SqlConnection thisConnection = new SqlConnection(connStr))
            {
                using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
                {
                    thisConnection.Open();
                    count = (int)cmdCount.ExecuteScalar();
                }
            }
            return count;
        }
        catch (Exception ex)
        {
            VDBLogger.LogError(ex);
            return 0;
        }
    }

Comments

1

This works for me

using (var context = new BloggingContext())
{
   var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}

For more information consult: https://learn.microsoft.com/es-es/ef/ef6/querying/raw-sql?redirectedfrom=MSDN

Comments

0

Use this its working

        string strQuery = "SELECT * FROM staff WHERE usertype='lacturer'";

        connect.Open();

        SqlCommand cmd = new SqlCommand(strQuery, connect);
        SqlDataAdapter OleDbDa = new SqlDataAdapter(cmd);
        DataSet dsData = new DataSet();
        OleDbDa.Fill(dsData);

        connect.Close();
        
        std.Text = dsData.Tables[0].Rows.Count.ToString();

2 Comments

No, you don't want to load an entire table into a DataSet just to get the row count. Yes, it works, but if your database contains 100 MB of data, you will use (approximately) 100 MB of network traffic and 100 MB of RAM just to get a single integer. This is a bad practice.
thank you so much. I have learned something new today
0

I used this method in my own application to count the number of active users within the program. This can be easily manipulated for your own use.

        con.open();
        string ActiveUsers = "SELECT * FROM Devices WHERE Status='" + "Online" + "'";
        SqlCommand cmd = new SqlCommand(ActiveUsers, con);
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        con.Close();

        Users.Text = ds.Tables[0].Rows.Count.ToString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.