epiphany
epiphany

Reputation: 766

Else statement fails to work within a while loop

Below is my code to connect to the database using MySqlDataReader. Now the if statement is working fine but the else statement doesnt. When i use the debug function in VS it kept skipping the else statement and jump to the reader.Close();. Any idea. Thanks

private void db()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

    MySqlConnection connection = new MySqlConnection(constr);
    connection.Open();
    MySqlCommand command = connection.CreateCommand();

    command.CommandText = "SELECT * FROM user Where user_id ='" + Userid.Text + "'" + "And password='" + Password.Text + "'";

    MySqlDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        if (!reader.IsDBNull(0))
        {
            Label1.Text = reader["user_id"].ToString();
        }
        else
        {
            Label1.Text = "nodata";
        }
        reader.Close();
    }
}

Upvotes: 0

Views: 103

Answers (1)

derpirscher
derpirscher

Reputation: 17382

First of all: Don't use string concatenation for building queries, but use parameterized queries!

As for your problem: I assume this query will only return either 1 or 0 rows, so you don't need the loop but just check

if (reader.Read()) {
    //...
} 

Using SELECT * with column indexes is potentially dangerous, because you may not know what the "first" column returned is. I would suggest name your desired columns in the query

SELECT user_id, user_name ... FROM ... 

What is the value of the first column returned? I assume, it's the user_id. Thus, this can never fulfill the condition IsDBNull(0) because user_id is your matching criterion in the WHERE clause. If your WHERE clause does not match any record in the table, reader.Read() will already fail, so you'll never get to your else branch.

Furthermore, I would suggest a using clause, which will dispose the reader automatically, so you don't have to care about closing it.

command.CommandText = "SELECT user_id, foo, bar from user where user_id = @userid and password = @password";
command.Parameters.AddWithValue("@user_id", UserId.Text);
command.Parameters.AddWithValue("@password", Passowrd.Text);

using (MySqlDataReader reader = command.ExecuteReader()) {
    if (reader.Read()) {
        Label1.Text = reader["user_id"].ToString();
    } else {
        Label1.Text  ="nodata";
    }
}

Upvotes: 2

Related Questions