简体   繁体   English

基于 Java 中的用户输入构建动态 SQL 查询

[英]Building a dynamic SQL query based on user input in Java

If I have a search module which has the following: search box, dropdown 1, dropdown 2.如果我有一个包含以下内容的搜索模块:搜索框、下拉菜单 1、下拉菜单 2。

And I have a query like this:我有这样的查询:

SELECT * FROM MY_TABLE where q1 = 'searchBox' AND q2 = 'dropdown1' AND q3 = 'dropdown2'

How can I make that query dynamic depending on user filter, so if the user only fills the search box, the query will be:我怎样才能根据用户过滤器使查询动态化,所以如果用户只填写搜索框,查询将是:

SELECT * FROM MY_TABLE where q1 = 'searchBox'

If the user fills search box and dropdown1, the query will be:如果用户填写搜索框和下拉列表 1,查询将是:

SELECT * FROM MY_TABLE where q1 = 'searchBox' AND q2 = 'dropdown1'

and if the user doesn't fill anything, the query will be:如果用户没有填写任何内容,查询将是:

SELECT * FROM MY_TABLE

I am using Java.我正在使用 Java。

There are frameworks that can help with this: 有一些框架可以帮助您:

If you'd like to create a quick and simple solution, you can do something like the following: 如果您想创建一个快速简单的解决方案,则可以执行以下操作:

List<String> params = new ArrayList<>();
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM MY_TABLE WHERE 1 = 1");

if (searchBox != null) {
    sb.append(" AND q1 = ?");
    params.add(searchBox);
}

if (dropdown1 != null) {
    sb.append(" AND q2 = ?");
    params.add(dropdown1);
}

if (dropdown2 != null) {
    sb.append(" AND q3 = ?");
    params.add(dropdown2);
}

PreparedStatement preparedStatement = connection.prepareStatement(sb.toString());
for (int i = 1; i <= params.size(); i++) {
    preparedStatement.setString(i, params.get(i));
}

ResultSet resultSet = preparedStatement.executeQuery();

To improve upon the code provided by @blacktide改进@blacktide提供的代码

PreparedStatement preparedStatement = connection.prepareStatement(sb.toString());
for (int i = 1; i <= params.size(); i++) {
    preparedStatement.setString(i, params.get(i));
}

You would instead want the line within the for loop to be相反,您希望 for 循环中的行是

preparedStatement.setString(i, params.get(i-1));

Since arrays start at 0, we'd want to grab that zeroth index to set the first value added to the list to the first value to be updated in the SQL string.由于 arrays 从 0 开始,我们想要获取第零个索引以将添加到列表中的第一个值设置为 SQL 字符串中要更新的第一个值。 Otherwise you would grab the second value within params which would not be the intended value.否则你会获取 params 中的第二个值,这不是预期的值。

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

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