C # using error like MYSQL ExecuteScalar ()

I use the MySQL library in Xamarin to connect to my database. I call the command ExecuteScalar()to check if the user exists in my database.

I returned return ExecuteScalar()to Int32 and saved it in an Int32 variable called userCount, but Visual Studio throws an error cast is not validwhen trying to call(int32)checkUser.ExecuteScalar();

Here's how this could be done in the documentation , so I'm 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
}
+4
source share
2 answers

You are connected with System.Data.SqlClient, notMySQL.Data.MySqlClient

https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-sql-command.html

There is an example here -

object result = cmd.ExecuteScalar();
        if (result != null)
        {
            int r = Convert.ToInt32(result);
            Console.WriteLine("Number of countries in the world database is: " + r);
        }

, null int32

0

. , ExecuteScalar() , int. , int.

:

Int32 userCount = (Int32)checkUser.ExecuteScalar(); //error is here

To:

int userCount = (int)(long)(checkUser.ExecuteScalar());

.


Btw , :

using (MySqlCommand cmd = connection.CreateCommand())
{
    cmd.CommandText = "SELECT COUNT(*) FROM <MyCoolDatabase> WHERE Userid = @user";
    cmd.Parameters.AddWithValue("@user", username);

    int userCount = (int)(long)(checkUser.ExecuteScalar());
    if (userCount > 0)
    {
        //work
    }
}
-1

Source: https://habr.com/ru/post/1676419/


All Articles