如何修复此功能始终返回false

时间:2019-05-08 22:27:25

标签: java sql jsp jdbc

我编写了此函数来检查在数据库中给出名称的id,但是它始终返回false

public boolean checking(String name,String Id_number,String tableName){
    if(conn==null){
        System.out.println("db is not connect,is gonna connect");
        connect();
    }
    try{
        Statement stmt=conn.createStatement();
        ResultSet rs=stmt.executeQuery("select * from "+tableName+" where name ="+"'"+name+"'");
        if(Id_number.equals(rs.getString(4))){
            return true;
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    return false;
}

我该如何解决

1 个答案:

答案 0 :(得分:1)

创建ResultSet时,它指向结果的“ before-first”行。您需要尝试将其前进到第一行(使用next()),然后比较其内容。如果没有这样的行,则可以返回false

public boolean checking(String name, String id_number, String tableName){
    if (conn==null) {
        connect();
    }

    try{ 
        Statement stmt = conn.createStatement();

        // Side note: Depending on where the parameters come from, this may be vulnarable
        // to an SQL Injection attack.
        // Make sure you properly validate/sanitize the arguments
        ResultSet rs = stmt.executeQuery("select * from " + tableName + " where name = " + "'"+name+"'");

        // Check if there's even such a row:
        if (!rs.next()) {
            return false;
        }

        // Check the id number
        return Id_number.equals(rs.getString(4));

    } catch(Exception e){
        e.printStackTrace(); // Or some proper handling...
    }
    return false;
}