gpt4 book ai didi

java - 如何修复这个函数总是返回 false

转载 作者:行者123 更新时间:2023-11-30 05:39:02 25 4
gpt4 key购买 nike

我编写了这个函数来检查 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;
}

如何解决这个问题

最佳答案

当创建 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;
}

关于java - 如何修复这个函数总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56049851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com