首页 > 解决方案 > 在任何值的情况下,带有一些 where 条件的准备好的语句

问题描述

我已经准备好了声明

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

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

标签: javamysqlsqljdbc

解决方案


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


推荐阅读