【问题标题】:Data Reader and Invalid attempt to read when no data is present数据读取器和不存在数据时尝试读取无效
【发布时间】:2014-03-06 06:17:24
【问题描述】:

这是我的代码:

protected void logujButton_Click(object sender, EventArgs e)
{
    string user = "data source=myHostServer; database = myDataBase; user id=myLogin; password=myPassword";
    SqlConnection con2 = new SqlConnection(user);
    con2.Open();

    string loguj = "select count(*) from uzytkownik where Login = '"+ logujTextBox.Text +"'";
    SqlCommand command = new SqlCommand(loguj, con2);
    int wartosc = Convert.ToInt32(command.ExecuteScalar().ToString());
    con2.Close();

    if (wartosc == 1)
    {
        con2.Open();
        SqlCommand pobierzHaslo = new SqlCommand("select Haslo from uzytkownik where Login = '" + logujTextBox.Text + "'", con2);
        SqlDataReader rdr = pobierzHaslo.ExecuteReader();
        string haslo = rdr["Haslo"].ToString();
        if (haslo == hasloTextBox.Text)
        {
            errorLabel.Text = "Prawidlowe Haslo !";
        }
        else
        {
            errorLabel.Text = "Zle haslo !";
        }
    }
    else 
    {
        errorLabel.Text = "Taki uzytkownik nie istnieje !";
    }
}

当我按下按钮时,出现此错误:“没有数据时读取尝试无效”。你能告诉我,我在哪里做错了吗?感谢您的建议!

【问题讨论】:

  • 调试您的代码并告诉我们发生在哪一行。
  • "string haslo = rdr["Haslo"].ToString();"这一行有问题
  • 请阅读parameterized queries。您当前的方法容易受到 SQL 注入攻击。

标签: asp.net sqldatareader


【解决方案1】:

你还没有从读者那里读到任何东西。你必须调用 Read() 方法:

 SqlDataReader rdr = pobierzHaslo.ExecuteReader();
 if (rdr.Read())
 {
        string haslo = rdr["Haslo"].ToString();
        ....
 }

【讨论】:

  • 谢谢!现在它正在工作,但有一些我不明白的错误。阅读器正确地从数据库接收值,但 prgoram 正在“else”语句中执行代码,而不是“if”中。这是为什么 ?。我知道 redader 的价值是正确的,因为在“else statemnet”中我更改了 'errorLabel.Text = “Zle haslo !”;'进入'errorLabel.Text = haslo;'。
  • 好的,我找到了解决方案。问题出在数据库上。我更改了列数据类型并且工作正常。
【解决方案2】:

如果您有权访问 SSMS,请直接在查询窗口中运行查询,并确保您能取回数据。您的查询可能不好。根据错误消息的文本,这很可能是来自 SqlDataReader 的 ExecuteReader 方法的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多