【发布时间】:2013-02-27 20:36:00
【问题描述】:
所以我有 4 个菜单选择(产品、位置、课程类型和类别),所有这些都可以为空(使用 JSF 编程,但这应该与这个问题无关,因为它是一个 SQL 问题)。
菜单选择将向托管 bean 发送用户选择的变量,并使用准备好的语句使用用户选择的菜单中的信息(如果有)搜索数据库表。
如果用户让菜单项为空,它应该搜索所有内容。
如果用户留下 1 或 2 或 3 个带有信息的菜单项,而另一个为空,则应进行相应的搜索。
我的问题是,如果 bean 中没有一堆 if/then 语句附加到每个相应的 sql 语句,我该如何做到这一点?
或者有没有更好的 sql 语句我可以做到这一切?
我在 Java 中使用准备好的语句。
我试过了:
if (product != null && location != null && courseType != null && category != null) {
pstmt = conn.prepareStatement("select * FROM Courses WHERE "
+ "product = ? "
+ "and location = ? "
+ "and courseType = ? "
+ "and category = ?");
pstmt.setString(1, product);
pstmt.setString(2, location);
pstmt.setString(3, courseType);
pstmt.setString(4, category);
} else if (product == null && location != null && courseType != null && category != null) {
pstmt = conn.prepareStatement("select * FROM Courses WHERE "
+ "location = ? "
+ "and courseType = ? "
+ "and category = ?");
pstmt.setString(1, location);
pstmt.setString(2, courseType);
pstmt.setString(3, category);
}
etc 等等,但是对于每个 1 为空而不是其他情况的情况,我必须这样做 16 次? 一定有更聪明的方法(要么使用 1 条 sql 语句,要么只使用几条 java if/then 语句?)
感谢 Luiggi Mendoza 更新!我的代码是这样工作的:
pstmt = conn.prepareStatement("select * FROM Courses WHERE "
+ "(product = ? or ? is null) "
+ "and (location = ? or ? is null) "
+ "and (courseType = ? or ? is null)"
+ "and (category = ? or ? is null)");
pstmt.setString(1, product);
pstmt.setString(2, product);
pstmt.setString(3, location);
pstmt.setString(4, location);
pstmt.setString(5, courseType);
pstmt.setString(6, courseType);
pstmt.setString(7, category);
pstmt.setString(8, category);
rset = pstmt.executeQuery();
更新是的,对于不同的 mysql 数据库(可能是不同的版本或其他东西),我必须使用 = "" 而不是 null
【问题讨论】: