Reputation: 91
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?
Upvotes: 3
Views: 2601
Reputation: 153
select CASE WHEN Count(*) > 0 THEN 1 ELSE 0 END as UserExists from.....
Upvotes: 0
Reputation: 32681
You can resolve your problem by
userexists = (int)c.ExecuteScalar() > 0.
But, I have my reservations over this approach as well. You should check for userid rather than username. Multiple users can have same username whereas userid will be unique.
Upvotes: 0
Reputation: 204766
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;
Upvotes: 3
Reputation: 7214
change this line :
userexists = (bool)c.ExecuteScalar();
to this :
userexists = (int32)c.ExecuteScalar() > 0;
Upvotes: 3