0

下面是我使用 MySqlDataReader 连接到数据库的代码。现在 if 语句工作正常,但 else 语句没有。当我在 VS 中使用调试功能时,它一直跳过 else 语句并跳转到 reader.Close();。任何的想法。谢谢

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();
    }
}
4

1 回答 1

2

首先:不要使用字符串连接来构建查询,而是使用参数化查询!

至于你的问题:我假设这个查询只会返回 1 或 0 行,所以你不需要循环,只需检查

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

与列索引一起使用SELECT *可能很危险,因为您可能不知道返回的“第一”列是什么。我建议在查询中命名您想要的列

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";
    }
}
于 2018-07-07T13:25:41.760 回答