将检索到的数据从数据库分配给字符串变量

时间:2013-11-08 23:52:37

标签: java mysql

我正在创建一个系统,用于验证已在数据库中定义的凭据与在jTextfield中输入的凭据。当我在if-else语句中输入条件时,它表示不能将String转换为boolean。请帮忙。

 Connection con = (Connection) DriverManager.getConnection (host, uName, uPass);
        Statement stmt = (Statement) con.createStatement ();
        //login is a table in my database,password a tuple
        String SQL = "SELECT password FROM login;";
        ResultSet password = stmt.executeQuery (SQL);

        String pass = adminpassword.getText();
        String sqlpass = password.getString("password");
//error shows on if else below
        if(sqlpass = pass){
            JOptionPane.showMessageDialog(null,"You have entered an incorrect password,please try again.","Incorrect Password",JOptionPane.WARNING_MESSAGE);
        }
        else{
            String passconfirm = "SELECT admin_id WHERE password = 77353";
            ResultSet confirmpass = stmt.executeQuery(passconfirm);
            JOptionPane.showMessageDialog(null,"Welcome","Welcome " + confirmpass,JOptionPane.INFORMATION_MESSAGE);
            Countyinfo proceed = new Countyinfo();
            proceed.setVisible(true);
        }
        }
        catch(SQLException err){
         System.out.println (err.getMessage());
        };

2 个答案:

答案 0 :(得分:1)

相等性的布尔运算符是==,而不是=(它是赋值运算符)。赋值操作将始终计算为分配给其左值的值。

这就是sqlpass = pass评估为String的原因。 sqlpass == pass将评估为boolean

编辑: 不过,比较String的标准方法是使用.equals方法,如下所示:

if(sqlpass.equals(pass))

答案 1 :(得分:1)

您的if语句表达式中有一项作业,该作业返回String而不是必需的boolean

if (sqlpass = pass) {

应该是

if (sqlpass.equals(pass)) {

比较Strings==运算符比较Object引用而非内容)