Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql get number of rows

Tags:

c#

.net

mysql

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?

like image 886
YosiFZ Avatar asked Jun 24 '13 21:06

YosiFZ


People also ask

How can I get total number of rows in MySQL?

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.

How do I find the number of rows in SQL?

The COUNT() function returns the number of rows that matches a specified criterion.

How do I count rows in a column in MySQL?

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) .

How can we get the number of records or rows?

The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.


3 Answers

Try this

using (MySqlCommand cmd = new MySqlCommand(commandLine, connect))
{
    connect.Open();
    return Convert.ToInt32(cmd.ExecuteScalar());
}
like image 80
MDMalik Avatar answered Oct 28 '22 01:10

MDMalik


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 (!)

like image 26
Fabian Bigler Avatar answered Oct 28 '22 02:10

Fabian Bigler


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.

like image 24
Michael Knowles Avatar answered Oct 28 '22 02:10

Michael Knowles