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

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

        try
        {
            conn.Open();
            Console.WriteLine("Successfully connected to  SQl Server Database as " + csb.UserID);
            Console.WriteLine();
//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;
                Console.WriteLine(sqdaar[0]);
                Console.WriteLine(sqdaar[1]);
                Console.WriteLine(sqdaar[2]);
            }
            

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

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            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

/localhost/empClass/dataconn/

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

I had 3 Rows in my database table

Leave a Reply

Your email address will not be published. Required fields are marked *