You are currently viewing How to check number of rows in Database table from MVC Dot Net

How to check number of rows in Database table from MVC Dot Net

This post contains affiliate links. Read the full disclosure here.

Create or Open a Dot Net MVC Application

Go to the controller Class where you wants to create database connection

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data.SqlClient;

using Microsoft.AspNetCore.Mvc;

namespace test.Controllers

public class empClass : Controller

//Method Starts
    public string dataconn()
        SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
        csb.DataSource = "ServerName";
        csb.InitialCatalog = "database name";
        csb.IntegratedSecurity = true;
        csb.UserID = "sa";
        csb.Password = "password";

        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = csb.ToString();

            Console.WriteLine("Successfully connected to  SQl Server Database as " + csb.UserID);
//Database Data extract Section
            SqlCommand sqlcmd = conn.CreateCommand();
            sqlcmd.Connection = conn;
            sqlcmd.CommandType = System.Data.CommandType.Text;
            sqlcmd.CommandText = "select InputA,InputB,Winner from TB_Rules";
            SqlDataAdapter sdar = new SqlDataAdapter(sqlcmd);

            SqlDataReader sqdaar = sqlcmd.ExecuteReader();
            int numrws = 0;
            bool rcvcnt = sqdaar.HasRows;
            while (sqdaar.Read())
                numrws = numrws + 1;

            return "Successfully connected to SQl Server Database as " + csb.UserID + " Has Rows = " + rcvcnt + " No Of Rows Fetched : " + numrws;

        catch (Exception ex)
            return conn.ConnectionString + "Error connected to  SQl Server Database as " + ex.Message;


Excess Database Table from MVC DOT Net

Save the Controller Class and Run your Application

If Connection Details are correct below successful message will be display in internet Explorer


Successfully connected to SQl Server Database as sa Has Rows = True No Of Rows Fetched : 3

I had 3 Rows in my database table


Hi, I am passionate about technology be it hardware or software. I like to write blogs and help people.

Leave a Reply