Search code examples
c#asp.netado.netoraclecommand

Get the value of Count from database rows in ASP.NET web app


The query is correct but I want to access the number of rows and show in the front-end page. This code is throwing an error.

   protected void Page_Load(object sender, EventArgs e)
        {
            string constr = ConfigurationManager.ConnectionStrings["ConnectionString_cw"].ConnectionString;
            OracleCommand cmd = new OracleCommand();
            OracleConnection con = new OracleConnection(constr);
            con.Open();
            cmd.Connection = con;
            cmd.CommandText = @"SELECT COUNT (*) from dish";
            cmd.CommandType = CommandType.Text;

            DataTable dt = new DataTable("Dish");
            using (OracleDataReader sdr = cmd.ExecuteReader())
            {
                if (sdr.HasRows)
                {
                    dt.Load(sdr);
                    recordMsg.Text = sdr["count(*)"].ToString();
                }

            }
            con.Close();
        }

I am using Oracle as database and it is connected already.


Solution

  • As you need a single value there is no use of DataTable and DataReader you can simply use ExcuteScalar of command and get the values.

     command.ExecuteScalar();
    

    More Reading https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar?view=dotnet-plat-ext-5.0

    or simply

    recordMsg.Text=command.ExecuteScalar().ToString();
    

    So the whole code can be written as

    string constr = ConfigurationManager.ConnectionStrings["ConnectionString_cw"].ConnectionString;
    OracleCommand cmd = new OracleCommand();
    OracleConnection con = new OracleConnection(constr);
    con.Open();
    cmd.Connection = con;
    cmd.CommandText = @"SELECT COUNT (*) from dish";
    cmd.CommandType = CommandType.Text;
    recordMsg.Text=command.ExecuteScalar().ToString();
    

    It is also advisable to use using statement for better use of command and connection.