我一直收到 "Invalid attempt to read when no data is present",即使我确定存在记录

I keep getting "Invalid attempt to read when no data is present" even though I am sure a record exist

我一直在努力弄清楚为什么我会收到此错误消息,这让我感到困惑,因为我认为我已经应用了获得我想要的结果所需的一切。我该怎么做才能做到这一点。

private void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            // Receive user input from login screen
            string username = txtUsername.Text;
            string password = txtPassword.Text;

            // Test if user input is null or white space aka empty
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                MessageBox.Show("Please enter both username and password");
            else
            {
                // Establish connection with database
                SqlConnection cn = new SqlConnection(@"SERVER=KACY-PC\SQLEXPRESS2014;DATABASE=hardwareMgmt;Integrated Security=True");
                cn.Open();

                SqlCommand cmd = new SqlCommand();
                cmd.Connection = cn;

                string strSQL = "SELECT * FROM tbl_user WHERE username = '" + username + "' AND password = '" + password + "'";
                cmd.CommandText = strSQL;

                SqlDataReader dr = cmd.ExecuteReader();

                // Count number of record
                int count = 0;
                while (dr.Read())
                    count += 1; MessageBox.Show(Convert.ToString(count));
                dr.Read();

                // Validate whether user has logged in before and display appropriate 
                if (count == 1 && dr["first_login"].ToString() == "N")
                    MessageBox.Show("Welcome back '" + dr["first_name"].ToString() + "' '" + dr["last_name"].ToString() + "'", "Welcome back", MessageBoxButtons.OK);
                else if (count == 1 && dr["first_login"].ToString() == "Y")
                    MessageBox.Show("Hello " + dr["first_name"].ToString() + "' '" + dr["last_name"].ToString() +
                        "\nIt appears that you are logging in for the first time" +
                        "\nor your password got reset", "Welcome", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else if (count > 1)
                    MessageBox.Show("Duplication in user account \nPlease contact System Administrator", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show("Invalid Username or Password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

在登录 window 中输入凭据后,我不断收到以下结果。我确信在数据库中找到了该记录,但它只是没有读取它。

你的

dr.Read();

行是不必要的,因为在你的

之后
while (dr.Read())
    count += 1; MessageBox.Show(Convert.ToString(count));

代码,将没有下一条要读取的记录,这就是为什么会出现此错误。

正如 Ivan 评论的那样,您无法读取 while 之后的任何数据。这就是为什么无论想阅读 first_loginfirst_namelast_name 等...专栏,都必须在迭代 reader 的同时阅读。这就是为什么要考虑先改变你的逻辑。

对于我自己,当我想读取值而不是 dr[...] 语法时,我更喜欢使用 SqlDataReaderGetXXX methods。在我看来,这更具可读性。

还有一些事情;

  • 您应该始终使用 parameterized queries by the way. This kind of string concatenations are open for SQL Injection 攻击。

  • 不要将密码存储为纯文本。阅读:Best way to store password in database

  • 使用using statement自动配置你的连接、命令和reader。