简体   繁体   English

Java SQL 查询结果集总是返回 null 找不到解决办法

[英]Java SQL Query Resultset always returns null can't find solution

I am trying to check if a user entered Username and password matches one in my data base however what ever I try the result set still comes up null.我正在尝试检查用户输入的用户名和密码是否与我的数据库中的用户名和密码匹配,但是我尝试过的结果集仍然为空。 the sql varible is set to the username and the pass is set to the password however when ever i enter the correct details it shows up with no results sql 变量设置为用户名,密码设置为密码,但是当我输入正确的详细信息时,它会显示没有结果

public boolean Login(){
    boolean valid = true;
        try {
            String stmt = "SELECT * From TBLUser where User = ? and Password = ? ;";
            PreparedStatement pstmt = conn.prepareStatement(stmt);
            pstmt.setString(1, sql); pstmt.setString(2, pass);
            ResultSet rs = pstmt.executeQuery();
            if(!rs.next()){
                valid = false;
            }
        } catch (SQLException e) {
            System.err.println("Error: "+e);
        }
    return valid;
}

Also, better practice:另外,更好的做法是:

public boolean Login(String asql, String apass){
    boolean valid = true;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

        try {
            String stmt = "SELECT * From TBLUser where User = ? and Password = ? ";
            pstmt = conn.prepareStatement(stmt);
            pstmt.setString(1, asql); 
            pstmt.setString(2, apass);

            rs = pstmt.executeQuery();

            valid = (!rs.next());

        } catch (SQLException e) {
            e.printStaceTrace();
        } finally { // cleanup
          try { rs.close(); } catch (Exception ex) {}
          try { ps.close(); } catch (Exception ex) {}
        }
    return valid;
}

The problem with the application is not the code but the database as User one of the column names is a reserved word so this change fixed the problem thanks to @Grayson for all the help应用程序的问题不是代码,而是数据库作为列名之一的用户是保留字,因此此更改解决了问题,感谢@Grayson 提供的所有帮助

public boolean Login(){
boolean valid = true;
    try {
        String stmt = "SELECT * From TBLUser where UserName = ? and Password = ? ;";
        PreparedStatement pstmt = conn.prepareStatement(stmt);
        pstmt.setString(1, sql); pstmt.setString(2, pass);
        ResultSet rs = pstmt.executeQuery();
        if(!rs.next()){
            valid = false;
        }
    } catch (SQLException e) {
        System.err.println("Error: "+e);
    }
return valid;

} }

Use unit cap with " " to save your column-Table like使用带有“”的单位上限来保存您的列表,例如

Create Table "TBLUser"{ "User" char... "Password"... }创建表“TBLUser”{“用户”字符...“密码”...}

similarly, your select query will change String stmt = "SELECT * From \\"TBLUser\\" where \\"User\\" = ? and \\"Password\\" = ? "同样,您的选择查询将更改 String stmt = "SELECT * From \\"TBLUser\\" where \\"User\\" = ? and \\"Password\\" = ? "

This should work.这应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM