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++;
}
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:准备好语句后,需要设置参数,并注意使用正确的索引:
我通过根据输入数据使用4个不同的准备好的语句来解决此问题。
这是“动态SQL”的情况。您可以手动执行此操作,也可以使用ORM。
让我们看一下手动情况:
现在,如果您有10个参数,那么ORM确实有很大帮助。它们几乎都以一种非常不错的方式支持动态SQL。