while(reader.Read())函数不工作-MySql,C#



我的代码中有一个错误,无法解决。我希望其他人也能做到。

  public void Login(object Sender, EventArgs e)
    {
        conn.OpenConn();
            if (usernametxt.Text == "" || passwordtxt.Text == "")
            {
                ErrorLoglbl.Text = "fill in all fields";
            }
            else
            {
                conn.OpenConn();
                    string query = "SELECT * FROM gebruikers";
                    MySqlCommand cmd = new MySqlCommand(query, conn.mycon);
                    //Create a data reader and Execute the command
                    MySqlDataReader dataReader = cmd.ExecuteReader();
                    //Read the data and store them in the list
                    while (dataReader.Read())
                    {
                        ErrorLoglbl.Text = "test";
                    }
                }
            }

我想做的是比较输入的usernametxt。数据库中包含用户名字段的文本。密码也是如此。

试着在那一行调试代码;gebruikers";不包含任何数据的表将说明读取器的执行,因为没有要读取的数据。

考虑到表中有记录,请尝试使用";使用语句";因此,reader对象将在语句末尾自动处理,有时会发生故障,因为前一语句中的reader未正确处理,并引发异常。您可以使用try/catch语句捕获该异常

  public void Login(object Sender, EventArgs e)
{
    conn.OpenConn();
        if (usernametxt.Text == "" || passwordtxt.Text == "")
        {
            ErrorLoglbl.Text = "fill in all fields";
        }
        else
        {
             try{
                     string query = "SELECT * FROM gebruikers";
                MySqlCommand cmd = new MySqlCommand(query, conn.mycon);
                //Create a data reader and Execute the command
                
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                   while (reader.Read())
                   {
                       MessageBox.Show("reading a record..");
                   }
                }
                }
                catch(Exception e)
                {
                      MessageBox.Show(e.ToString());
                }
                
            
        }
      conn.Close();

}

不要忘记关闭连接:)

最新更新