带有任何条件的准备好的语句,

时间:2020-04-08 19:59:44

标签: java mysql sql jdbc

我已经准备好类似的声明

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

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

3 个答案:

答案 0 :(得分:2)

这是“动态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。

答案 1 :(得分:1)

准备好的语句不会覆盖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++;
}

答案 2 :(得分:0)

我通过根据输入数据使用4个不同的准备好的语句来解决此问题。

相关问题