带有某些条件的准备好的语句(如果有任何值)

我准备了这样的声明

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

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

评论
  • kautem
    kautem 回复

    Which parts of the SQL statement should be present is not covered by prepared statements (unless you get creative). Typically the solution is generating the conditions in the where clause dynamically, for example:

    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++;
    }
    
  • 类敏思
    类敏思 回复

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

  • She
    She 回复

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