【问题标题】:Prepared statement with some where condition in case of any value在任何值的情况下,带有一些 where 条件的准备好的语句
【发布时间】:2020-04-08 19:59:44
【问题描述】:

我已经准备好了类似的声明

select * from books where author = ? and theme = ?

我不知道该怎么做,如果用户选择选项“任何作者”或“任何主题”,我应该为准备好的语句设置什么?

【问题讨论】:

  • 您可以为作者条件传递更多参数,对于 ej :如果用户选择任何作者,则选择 * from books where (0 = any or author = ? );那么任何值都必须为 0,并且选择查询获取所有作者,否则用户选择和作者,则任何值必须为 1,并且查询采用 or 条件。对不起我的英语。
  • 我不明白你的意思。我应该使用类似 statement.setInt(1, authorId);所以我不明白如何传递更多的值。
  • 好的,any 可以作为作者的另一个参数。 select * from books where (0 = ? or author = ? );并在您的代码中 if(author.isAny()) 将 0 或 1 传递给第一个参数并在第二个参数中为空,
  • 我明白了,但我认为它的解决方案很糟糕,因为它是某种糟糕的架构。

标签: java mysql sql jdbc


【解决方案1】:

这是“动态 SQL”的情况。您可以手动完成,也可以使用 ORM。

我们来看看手动案例:

String sql;
if (author == null) {
  if (theme == null) {
     sql = "select * from books";
  } else {
     sql = "select * from books where theme = ?";
  }
} else {
  if (theme == null) {
     sql = "select * from books where author = ?";
  } else {
     sql = "select * from books where author = ? and theme = ?";
  }
}
PreparedStatement ps = con.createStatement(sql);
int param = 1;
if (author != null) {
  ps.setString(param++, author);
}
if (theme != null) {
  ps.setString(param++, theme);
}
// The rest is just running the SQL and read the ResultSet.

现在,如果您有 10 个参数,那么 ORM 真的很有帮助。它们几乎都以非常好的方式支持动态 SQL。

【讨论】:

  • 感谢您的详细回答,是的,这是选项。
【解决方案2】:

准备好的语句不包括 SQL 语句的哪些部分应该存在(除非您有创意)。通常,解决方案是动态生成where 子句中的条件,例如:

String sql = "select * from books where 1=1";
if (author != null) { 
    sql += " and author=?";
}
if (theme != null) { 
    sql += " and theme=?";
}

准备好语句后,您需要设置参数,注意使用正确的索引:

int parameterIndex = 1;
if (author != null) {
    preparedStatement.setString(parameterIndex, author);
    parameterIndex++;
}
if (theme != null) {
    preparedStatement.setString(parameterIndex, theme);
    parameterIndex++;
}

【讨论】:

  • 我不使用连接,只使用准备好的语句,你知道的,安全的东西。
  • 使用连接从固定常量块构建准备好的语句的 sql,不要使用它来填充参数。否则你会怎么做,为 N 个可能是可选的参数编写 2^N 个查询?
  • 哦,是的,对不起,我没有先了解你,你说得对,我可以在使用前根据输入参数构建准备好的语句。
【解决方案3】:

我根据输入数据使用 4 种不同的预处理语句来解决这个问题。

【讨论】:

  • hmm...这里不是四个案例而不是三个案例吗?
  • 一个案例,当我之前有任何作者和任何主题,所以我不计算这个,但你说得对,有4个案例。
猜你喜欢
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多