How I get the number of a rows in a Micorosft SQL table using C#?

How I get the number of rows in a table using C#?

Here is a step by step:

Step 1 – Create a new class: (attached click here: SQLTableRowCounter.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace SQLTableRowCounter
{
    class SQLTableRowCounter
    {
        private string mCountQuery;
        private SqlConnection mConnection;
        private int mNumberOfRows;

        public SQLTableRowCounter(String inTableName, SqlConnection inConnection)
        {
            mCountQuery = "SELECT COUNT(*) FROM " + inTableName;
            mConnection = inConnection;
            mConnection.Open();
            SqlCommand mCountQueryCommand = new SqlCommand(mCountQuery, mConnection);
            mNumberOfRows = (int)mCountQueryCommand.ExecuteScalar();
        }

        public int NumberOfRows
        {
            get { return mNumberOfRows; }
            set { mNumberOfRows = value; }
        }
    }
}

Step 2 – Now create the object and get the value:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace SQLTableRowCounter
{
    class Program
    {
        static void Main(string[] args)
        {
             string connectionString = @"Data Source = ServerName; user id=UserName; password=P@sswd!; Initial Catalog = DatabaseName;";
             SqlConnection connection = new SqlConnection(connectionString);
             SQLTableRowCounter qrc = new SQLTableRowCounter("TableName", connection);
             int numRows = qrc.NumberOfRows;
        }
    }
}

Leave a Reply