I am using the MySQL library in Xamarin to connect to my database. I am calling the ExecuteScalar() command to check if a user exists in my DB. 
I cast the return of ExecuteScalar()  to an Int32 and storing in a Int32 variable called userCount, but Visual Studio is throwing a cast is not valid error when I try to call (int32)checkUser.ExecuteScalar();
This is how it suggested to be done in the documentation, so I am confused. Here is my code:
using MySql.Data.MySqlClient;
using System.Data;
MySqlCommand checkUser = new MySqlCommand("SELECT COUNT(*) FROM <MyCoolDatabase> WHERE Userid = '" + username + "'", connection);
Int32 userCount = (Int32)checkUser.ExecuteScalar(); //error is here
if(userCount >0)
{
    //do stuff
}
                You linked to System.Data.SqlClient and not MySQL.Data.MySqlClient 
https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-sql-command.html
There is an example there -
object result = cmd.ExecuteScalar();
        if (result != null)
        {
            int r = Convert.ToInt32(result);
            Console.WriteLine("Number of countries in the world database is: " + r);
        }
Likely you are trying to cast null to int32
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