如何检索数据库中保存的字段?

时间:2014-03-15 11:07:22

标签: java mysql database netbeans

ValidateLogin.java

public boolean testLogin(LoginHandler user)
{
    String query = null;

    try
    {
        stmt = connect.createStatement();
        query = "SELECT * FROM users WHERE UserName = '"+user.getUsername()+"'";
        rs = stmt.executeQuery(query);
        rs.next();

        if(rs.getString(2).equals(user.getUsername()) && rs.getString(3).equals(user.getPassword()))
        {
            this.closeDB();
            return true;
        }
        else
        {
            JOptionPane.showMessageDialog(null,"Login Failed: Invalid Password");
        }
    }
    catch(SQLException ex)
    {
        JOptionPane.showMessageDialog(null,"Login Failed: Invalid Username");
    }

    this.closeDB();
    return false;
}

LoginHandler.java

public boolean verifyUser()
    {
        if(super.testLogin(this))
        {
            mainWindow mainwindow = new mainWindow();
            mainwindow.setVisible(true);
            return true;
        }
        return false;
    }

我已经在我的数据库中保存了用户名和密码字段。 我如何在loginWindow中检索它们?

每次我输入用户名和密码..它显示的信息是:"登录失败:密码无效"

有人帮忙吗?

1 个答案:

答案 0 :(得分:0)

试试这个

PreparedStatement ps = connect.prepareStatement("SELECT * FROM users WHERE UserName =?");
ps.setString(1,user.getUsername());
rs = ps.executeQuery();

使用列名而不是索引值 uname&传递是可变的

while (rs.next()) {
uname=rs.getString("UserName");
pass=rs.getString("Password");
}
if(uname.equals(user.getUsername()) && pass.equals(user.getPassword()))
    {
        this.closeDB();
        return true;
    }