开发者

SQL query does not return the correct count

开发者 https://www.devze.com 2023-03-01 14:14 出处:网络
I am trying to count the number of rows and pass that count value to do some logic. Below is the code:

I am trying to count the number of rows and pass that count value to do some logic. Below is the code:

   static public int GetNoImagesofM开发者_StackOverflow中文版akeID(int makeID)
{
    string sql = "Select COUNT(*) from makeImages";
    SqlDataAdapter da = new SqlDataAdapter(sql, ConnectionString);
    DataTable dt = new DataTable();
    da.Fill(dt);
    return Convert.ToInt32(dt.Rows.Count);
}

  protected void hideUnhideFileUpload(int makeID)
{

    int count = caravans.GetNoImagesofMakeID(makeID);
    if (count >= 10)
    {
        FileUpload2.Enabled = false;
    }

    else
    {
        FileUpload2.Enabled = true;
    }

}

I don't know for what reason the count is always 1. I checked the same query on SQL Server and it's working fine. But, here dt.rows.count always return 1.

Any help will be highly appreciated. Thanks.


The code is returning the number of rows rather than the result of the COUNT(*). That SQL statement will always just return a single row. Rather than filling a data adapter, you can just run the command:

SqlCommand cmd = someSQLConnection.CreateCommand();
cmd.CommandText = "Select COUNT(*) from makeImages";
return Convert.ToInt32(cmd.ExecuteScalar());


Your query is returning one row with one value (the count of rows), so dt.Rows.Count is correctly returning 1 (meaning 1 row returned by your query). Using a datatable, you would find the count returned by your query at dt.Rows[0][0] (row 0 column 0 of your datatable)


A count() always returns a row, regardless of how many rows it is counting. a count() is a scalar value. What you need to do is read the value returned in the recordset.

More information about counts in this question: SQL Return code from Select count(*)


Why are you getting the table row count, instead of the returned value from your count query, as this will return only single row?

return Convert.ToInt32(dt.Rows[0][0]);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号