yuyu
yuyu

Reputation: 19

C# reader.HasRows returns false all the time, even if I still have rows in the table

password = md5Crypt(password);
User u = null;
String sql = "SELECT * FROM user WHERE username='" + username + "' AND password='" + password + "'";
try
{
    conn.Open();
    MySqlCommand cmd = new MySqlCommand(sql, conn);
    MySqlDataReader reader = cmd.ExecuteReader();

    reader.Read();
    Console.WriteLine(reader.Read());


   if (reader.HasRows)
   {
        u = new User(reader["username"].ToString(), reader["password"].ToString(), reader["name"].ToString(), reader["role"].ToString());

   }
   else
   {
        u = null;
   }
   conn.Close();

}
catch (MySqlException e)
{
    Console.WriteLine(e.Message);
    conn.Close();
    return null;
}
return u;

Upvotes: 0

Views: 259

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460058

Never use string concatenatation to build your sql query. Instead use parameterized queries to prevent sql injection and other issues. That's the real issue.

But to fix your bug, you are calling MySqlDataReader.Read twice in a row. This will advance the reader to the next record. Instead do it only once:

if(reader.Read())
{
    u = new User(reader["username"].ToString(), reader["password"].ToString(), reader["name"].ToString(), reader["role"].ToString());
}
else
{
   u = null;
}
if(reader.Read())
{
    // bug detected, two user with same name and password, log this/throw an exception
}

Also use the using statemennt (or try-catch-finally) for the connection to ensure that it gets disposed/closed everytime, even in case of an error.

Upvotes: 4

Related Questions