Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# using MYSQL ExecuteScalar() type error

Tags:

c#

mysql

xamarin

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
}
like image 267
Barney Chambers Avatar asked May 05 '17 00:05

Barney Chambers


1 Answers

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

like image 53
Jason Bayldon Avatar answered Oct 23 '22 23:10

Jason Bayldon