简体   繁体   中英

Retrieving total count from database to c#

This query is been executed in database.

 select COUNT(*) from Patient_Data where  DummyValue = 'Y';

 104

I have to retrieve this number (104) from database to asp.net with c# so that when the count becomes zero I have to disable a button , How to retrieve this number from database into the code. It should be stored as integer .

I have tried these line of code in c#

    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand("select COUNT(*) as PatientCount from Patient_Data where  DummyValue = 'Y' ", cn))
        {
            try
            {

                cn.Open();

                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    int Patcount;
                    if (rdr.Read())
                    {
                        //Code Required

                    }
                }
            }
            catch (Exception ex)
            {

                // handle errors here
            }

        }


    }

use alias to get the count as below:

select COUNT(*) as PatientCount from Patient_Data where  DummyValue = 'Y';

Read the PatientCount value in code.

you can use GetInt32() function to get the count as int .
Note: you are passing the parameter values in your query which leads to Sql Injection Attacks, so you could use Parameterized Sql Queries to avoid them.

sample code is asbelow:

private int readPatientData()
        {
            int PatientCount = 0;              
            String strCommand = "select COUNT(*) as PatientCount from Patient_Data where  DummyValue = @MyDummyValue";
            using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString))
            {
                sqlConnection.Open();
                using (SqlCommand sqlcommand=new SqlCommand(strCommand,sqlConnection))
                {
                    sqlcommand.Parameters.Add(new SqlParameter("MyDummyValue", 'Y'));
                    SqlDataReader sqlReader = sqlcommand.ExecuteReader();
                    if (sqlReader.Read())
                        PatientCount = sqlReader.GetInt32(0);
                }
            }
            return PatientCount;
        }

I solved my issue with these lines of code.

        using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand("select COUNT(*) as PatientCount from Patient_Data where  DummyValue = 'Y' ", cn))
        {
            try
            {

                cn.Open();

                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    //int Patcount;
                    if (rdr.Read())
                    {
                        int Patcount = int.Parse(rdr["PatientCount"].ToString());
                        if (Patcount != 0)
                        {
                            Label3.Visible = true;
                            Label3.Text = "You have already have "+Patcount+" dummy records,Please update those records by clicking Update Dummy Records Link.";
                            btnSkipSubmit.Visible = false;
                        }
                        //Code Required


                    }
                }
            }
            catch (Exception ex)
            {

                // handle errors here
            }

        }


    }

As Per my knowledge there are three ways to do this:

  1. Using COUNT you can do this as below:

    select COUNT(*) as RowCount from Patient_Data where DummyValue = 'Y';

  2. Using ROW_NUMBER you can do this as below:

    Select ROW_NUMBER() OVER (ORDER BY Patient_Data.ID DESC) AS RowNumber from Patient_Data where DummyValue = 'Y';

  3. And there is another way but that way is only to get the row count and is the fastest way to get the row count in sql server according to me.

    SELECT Total_Rows= SUM(st.row_count) FROM sys.dm_db_partition_stats st WHERE object_name(object_id) = 'Patient_Data' AND (index_id < 2)

That's all

Update based on code change in question

You can write rdr.GetInt32(3); instead of code required in your code.

previous answer

You need to use ExecuteScalar method while executing your command. Here is the example from msdn:

static public int AddProductCategory(string newName, string connString)
{
    Int32 newProdID = 0;
    string sql =
        "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
        + "SELECT CAST(scope_identity() AS int)";
    using (SqlConnection conn = new SqlConnection(connString))
    {
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.Add("@Name", SqlDbType.VarChar);
        cmd.Parameters["@name"].Value = newName;
        try
        {
            conn.Open();
            newProdID = (Int32)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    return (int)newProdID;
}

In this example they are returning newly added product Id.

ExecuteScalar returns object that you can check for null and cast to number as you know with int.parse method or the best one you know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM