0

I want to count the number of rows in a MySql database and return the result in a label.

This is my code:

string connection = "SERVER= ###; PORT=###; DATABASE=###; UID=###; PASSWORD=###; CharSet=utf8;";

MySqlConnection mySqlCon = new MySqlConnection(connection);
MySqlCommand mySqlCmd = mySqlCon.CreateCommand();


mySqlCmd.CommandText = "Select count(*) as myCount from ###.###";
mySqlCon.Open();

int returnValue = (int) mySqlCmd.ExecuteScalar();

lblCLientNumber.Text = returnValue.ToString();

The error I get is: Specified cast is not valid.

But when I run the SQL command in phpMyAdmin the result is accurate.

I'm not sure where am I making a mistake.

1
  • What is the output of Console.WriteLine(typeof(mySqlCmd.ExecuteScalar()))? Commented Apr 6, 2018 at 16:19

3 Answers 3

2

Try using

returnValue = int.Parse(mySqlCmd.ExecuteScalar().ToString());

C# Is asking for an integer;

Take a look here Getting MySQL record count with C# this question has been asked before

Sign up to request clarification or add additional context in comments.

Comments

1

You are getting this error because ExecuteScalar function returns an object.

You could do the following:

int returnValue = int.Parse(mySqlCmd.ExecuteScalar().toString());

Comments

1

Try

int returnValue = Convert.ToInt32(mySqlCmd.ExecuteScalar());

However, my preference would be to reference the field. For example something like

using(MySqlCommand cmd = new MySqlCommand("Select count(*) as myCount from 
###.###", connection))
{
    using(MySqlDataReader rdr = cmd.ExecuteReader())
    {
        if(rdr.Read()) 
        {
            returnValue = Convert.ToInt32(rdr["myCount"]);
        }
    }
    rdr.Close();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.