将数据库中的值与字符串进行比较获取错误java.sql.sqlexception:没有为参数1指定值

jjhzyzn0  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(293)

我想创建一个登录页,只有管理员可以登录。
我的数据库:-tb\u用户用户id(pk)密码
-tb\u userauth user\u id(fk)objects\u id(包含用户的角色,如admin和customer)
这是我的程序:

private void cmd_loginActionPerformed(java.awt.event.ActionEvent evt) {                                          
    try{
        String sql = "select * from tb_users where user_id=? and password=?";           
        PST=conn.prepareStatement(sql);
        PST.setString(1,txt_userid.getText());
        PST.setString(2, txt_pass.getText());
        RS=PST.executeQuery();
        RS.close();

        String sql2 = "select * from tb_userauth where objects_id=?";           
        PST=conn.prepareStatement(sql2);
        RS=PST.executeQuery();
        String objek = "admin";
        String objek_id = RS.getString("objects_id");        

        if(RS.next()){

             if (objek.equals(objek_id)){

            JOptionPane.showMessageDialog(null,"user id and password correct");
             submenu1 sm1 = new submenu1();
             sm1.setVisible(true);
             sm1.pack();
             sm1.setLocationRelativeTo(null);
             sm1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             this.dispose();
        }else{
            JOptionPane.showMessageDialog(null,"check your password and user id ");
        } }  

    }catch (Exception e){
        JOptionPane.showMessageDialog(null,e);
    }

}

我得到了这样一个错误:java.sql.sqlexception:没有为参数1指定值
这让我很困惑,因为我已经使用string objek_id=rs.getstring(“objects_id”);
我的结果集有什么问题吗?

ckocjqey

ckocjqey1#

您错过了第二个准备语句的参数。我猜您在查询中犯了一些错误,所以我更改了查询并在更改中添加了注解。我没有运行和测试,所以可能会有一些问题。你可以有这个主意。

private void cmd_loginActionPerformed(java.awt.event.ActionEvent evt) {                                          
  try{
    String sql = "select * from tb_users where user_id=? and password=?";           
    PST=conn.prepareStatement(sql);
    PST.setString(1,txt_userid.getText());
    PST.setString(2, txt_pass.getText());
    RS=PST.executeQuery();
    String user_id = RS.getString("user_id"); //I don't know the type of use_id so I guess it as string

    RS.close();

    String sql2 = "select * from tb_userauth where user_id=?"; //I change object_id to user_id   

    PST=conn.prepareStatement(sql2);
    PST.setString(1,user_id);//this might not be string
    RS=PST.executeQuery();
    String objek = "admin";
    String objek_id = RS.getString("objects_id");        

    if(RS.next()){

         if (objek.equals(objek_id)){

        JOptionPane.showMessageDialog(null,"user id and password correct");
         submenu1 sm1 = new submenu1();
         sm1.setVisible(true);
         sm1.pack();
         sm1.setLocationRelativeTo(null);
         sm1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         this.dispose();
    }else{
        JOptionPane.showMessageDialog(null,"check your password and user id ");
    } 
  }  

  }catch (Exception e){
    JOptionPane.showMessageDialog(null,e);
  }

}

相关问题