如何为多用途结果制作单一方法?

时间:2016-03-25 20:39:02

标签: java mysql jsp servlets java-ee

我想提出三种类型的查询:

SELECT * FROM table
SELECT * FROM table WHERE code IN (...)
SELECT * FROM table WHERE code IN (...) AND username = 'xxx'
SELECT * FROM table WHERE username = 'xxx'

我知道我可以根据参数使用'if'句子构建查询,但我不确定它是否正常,例如我可以使用如下的preparedStatement:

SELECT * FROM table WHERE code IN(?) AND username = ?

但还有另一个问题,因为,如何避免(代码IN(?))或(AND用户名)取决于参数?我知道的唯一方法是使用字符串连接,如:

if (codes is not null) then
    query = query + " WHERE code IN( codes )"

if (username is not null) then
    query = query + " AND username = ? "

可以使用mysql在preparedStatement中构建一个唯一的查询吗?

LIKE:

SELECT * FROM table WHERE if (codes is not null) code IN ( ? ) AND if (username is not null) username = 'xxx'

2 个答案:

答案 0 :(得分:0)

这里看起来echo "<td><input form='$code' ...是'非常见'因素。您可以为Where子句传递字符串,如果没有则传递where portion。像这样......

null

doWork就像......

if you want `WHERE`...
    String WHERE = "code IN (...)"
    doWork(String WHERE);

else
    doWork(null);

答案 1 :(得分:0)

根据所需条件使用Java构建查询。

public String getQuery(String code, String username) {
    StringBuilder sb = new StringBuilder("SELECT * FROM `table`");

    boolean isCodeAdded = false;
    if (code != null) {
        sb.append(" WHERE `code` IN (?)");
        isCodeAdded = true;
    }

    if (username != null) {
        sb.append(isCodeAdded ? " AND" : " WHERE");
        sb.append(" `username` = ?");
    }
    return sb.toString();
}