【问题标题】:how to fix this function its allways return false如何修复这个函数它总是返回 false
【发布时间】:2019-09-26 17:24:08
【问题描述】:

我编写了这个函数来检查在数据库中给出名称的 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;
}

我该如何解决这个问题

【问题讨论】:

  • 您是否收到“java.sql.SQLException:在结果集开始之前”?
  • 不,我没有得到
  • 我想你是,因为你从不在结果集上调用next(),这将在任何正确实现的 JDBC 驱动程序上引发异常。

标签: java sql jsp jdbc


【解决方案1】:

创建ResultSet 时,它指向结果的“前第一”行。您需要尝试将其推进到第一行(使用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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    相关资源
    最近更新 更多