I try to get number of rows from a table with this :
string commandLine = "SELECT COUNT(*) FROM client";
using (MySqlConnection connect = new MySqlConnection(connectionStringMySql))
using (MySqlCommand cmd = new MySqlCommand(commandLine, connect))
{
connect.Open();
int count = (int)cmd.ExecuteScalar();
return count;
}
And i get the exception:
Specified cast is not valid.
Any idea how i can fix it?
To get the total number of rows in a MySQL database, you can use aggregate function SUM() along with inbuilt column TABLE_ROWS from INFORMATION_SCHEMA. TABLES. SELECT SUM(TABLE_ROWS) FROM INFORMATION_SCHEMA.
The COUNT() function returns the number of rows that matches a specified criterion.
The COUNT() function is an aggregate function that returns the number of rows in a table. The COUNT() function allows you to count all rows or only rows that match a specified condition. The COUNT() function has three forms: COUNT(*) , COUNT(expression) and COUNT(DISTINCT expression) .
The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.
Try this
using (MySqlCommand cmd = new MySqlCommand(commandLine, connect))
{
connect.Open();
return Convert.ToInt32(cmd.ExecuteScalar());
}
using (MySqlCommand cmd = new MySqlCommand(commandLine, connect))
{
connect.Open();
return Convert.ToInt32(cmd.ExecuteScalar());
}
EDIT: Make also sure to handle exceptions in your code (E.g. if there is SQL Connection Error).
Also, if it's not a COUNT(*)
the value returned by ExecuteScalar()
can be null (!)
If you wish to use the cast, you can use:
long count = (long)cmd.ExecuteScalar();
As mentioned above, COUNT in MySql returns BIGINT, hence casting with an int fails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With