Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExecuteScalar returns false for SQL count(*)

I have the following function to check if a user exists in my SQL table

private static bool  userexists(string user)
{
    bool userexists = false;

    SqlCommand c = new SqlCommand("SELECT COUNT(*) from UserTable where Username = @user");
    c.Parameters.Add(new SqlParameter("@user",user));
    using (SqlConnection con = new SqlConnection(Properties.Settings.Default.connectionString))
    {
        userexists = (bool)c.ExecuteScalar();
        return userexists;
    }
}

it returns false even if the user exists, what am I doing wrong?

like image 942
user2490355 Avatar asked Sep 11 '26 21:09

user2490355


2 Answers

Since you are getting back a number, you should cast it so and add a condition to get a bool result

userexists = (int) c.ExecuteScalar() > 0;
like image 100
juergen d Avatar answered Sep 13 '26 10:09

juergen d


change this line :

        userexists = (bool)c.ExecuteScalar();

to this :

        userexists = (int32)c.ExecuteScalar() > 0;
like image 25
jazzytomato Avatar answered Sep 13 '26 10:09

jazzytomato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!