gpt4 book ai didi

java - 搜索功能的 SQL 查询

转载 作者:可可西里 更新时间:2023-11-01 08:02:33 24 4
gpt4 key购买 nike

我想用多个 Java Swing 组件做一个搜索功能,用户可以按(姓名/国籍/专业/经验)进行搜索,结果将显示在 Jtable 中。

enter image description here

我只是在为 SQL 查询而苦苦挣扎,就好像用户只输入了“名称”一样,不会检索任何数据,因为它会像这样进入数据库 (name, null, null, null) 而我没有我的数据库中有任何空值。

所以我想检索具有该名称的所有数据,而不考虑其他列,但与此同时,如果他们也选择了特定的专业,例如,我想检索具有所选名称和专业的所有数据,依此类推.

我希望你能理解我的问题。

我当前的 SQL 语句:

public ArrayList<Applications> getData(String name, String nationality, String specialty, String experience) {

ArrayList<Applications> list = new ArrayList<Applications>();
Connection con = getConnection();
Statement st;
ResultSet rows;

try {
st = con.createStatement();

rows = st.executeQuery("SELECT * FROM applications WHERE name LIKE '%" + name+"%'"
+ " AND (nationality LIKE '" + nationality+"')"
+ " AND (specialty LIKE '" + specialty+"')"
+ " AND (experience LIKE '" + experience+"')");

Applications applications;

while(rows.next()) {
applications = new Applications(
rows.getInt("id"),
rows.getString("name"),
rows.getString("nationality"),
rows.getString("Specialty"),
rows.getString("experience")
);

list.add(applications);
}
} catch (SQLException ex) {
Logger.getLogger(MyQuery.class.getName()).log(Level.SEVERE, null, ex);
}

return list;
}

最佳答案

让我们看看您的查询:

   rows = st.executeQuery("SELECT * FROM applications WHERE name LIKE '%" +  name+"%'"
+ " AND (nationality LIKE '" + nationality+"')"
+ " AND (specialty LIKE '" + specialty+"')"
+ " AND (experience LIKE '" + experience+"')");

这里,由于只给出了name,其他值为null。如果您出于测试目的编写此代码:

String foo = null;
System.out.println(foo + "");

输出将是

"null"

因此,由于您的值为 null,因此生成的查询将是

   SELECT * FROM applications WHERE name LIKE '%Rowan Atkinson%'
AND (nationality LIKE 'null')
AND (specialty LIKE 'null')
AND (experience LIKE 'null')

首先,让我们确保在 null 的情况下得到空的 String:

   rows = st.executeQuery("SELECT * FROM applications WHERE name LIKE '%" +  ((name == null) ? "" : name)+"%'"
+ " AND (nationality LIKE '" + ((nationality == null) ? "" : nationality)+"')"
+ " AND (specialty LIKE '" + ((specialty == null) ? "" : specialty)+"')"
+ " AND (experience LIKE '" + ((experience == null) ? "" : experience)+"')");

下一个问题是您只将 % 放在 name 处,这也是不正确的,所以让我们解决这个问题:

   rows = st.executeQuery("SELECT * FROM applications WHERE name LIKE '%" +  ((name == null) ? "" : name)+"%'"
+ " AND (nationality LIKE '%" + ((nationality == null) ? "" : nationality)+"%')"
+ " AND (specialty LIKE '%" + ((specialty == null) ? "" : specialty)+"%')"
+ " AND (experience LIKE '%" + ((experience == null) ? "" : experience)+"%')");

现在阅读 YCF_L 的回答,以便您将命名参数用于 PreparedStatement。

关于java - 搜索功能的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50210415/

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