【问题标题】:Else statement fails to work within a while loopElse 语句无法在 while 循环内工作
【发布时间】:2018-07-07 12:57:09
【问题描述】:

下面是我使用 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();
    }
}

【问题讨论】:

  • 您是否打算将reader.Close() 放入循环中?如果有,为什么会有循环?
  • 你不需要循环,只需使用if (reader.Read())
  • reader.Close() 移出循环,将其更改为 if (reader.Read()),清理,重建,如果您仍然遇到问题,请告诉我们。
  • 这段代码没有多大意义。您不会关闭阅读器,然后尝试从中读取!此外,您的代码存在大量安全缺陷;阅读 SQL 注入。
  • 另外作为一个旁注,以在将来为您节省大量头痛(以及容易发现的安全漏洞),请切换到使用parameterized SQL queries。目前我可以使用用户名' or 1 = 1; drop table user; -- ,我会删除你的整个用户表。

标签: c# asp.net mysqldatareader


【解决方案1】:

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

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

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

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

SELECT user_id, user_name ... FROM ... 

返回的第一列的值是多少?我想,它是user_id。因此,这永远无法满足条件IsDBNull(0),因为user_id 是您在WHERE 子句中的匹配标准。如果您的WHERE 子句与表中的任何记录都不匹配,则reader.Read() 已经失败,因此您将永远无法到达您的 else 分支。

此外,我建议使用using 子句,它会自动处理阅读器,因此您不必关心关闭它。

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";
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-08
    • 2015-11-06
    • 2014-09-27
    • 2012-06-18
    • 1970-01-01
    • 2017-03-11
    • 2016-05-27
    • 2015-04-07
    相关资源
    最近更新 更多