java - 在任何值的情况下,带有一些 where 条件的准备好的语句
问题描述
我已经准备好了声明
select * from books where author = ? and theme = ?
我不知道该怎么做,如果用户选择选项“任何作者”或“任何主题”,我应该为准备好的语句设置什么?
解决方案
这是“动态 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。
推荐阅读
- laravel - 部署 Laravel 应用
- amazon-web-services - 无法在 AWS 中验证或上传 CloudFormation 模板
- filesystems - 非块文件系统
- javascript - Jquery code working fine until I included strict mode
- php - Trying to get value from PHP multi_query
- php - PHP. change value in Array of Arrays not working
- html - 使用附加路径生成的 Django 静态文件
- excel - 我想知道是否有一种方法可以根据 Excel VBA 中不同的列和单元格数据删除特定的行
- xml - 键字符串模式的 XML XPath
- database - 将每个两层的文件夹上移一层