例如,我有一个语句
"SELECT * FROM Reports WHERE StartDate >= ? WHERE EndDate <= ? AND Performer = ?"
但有时网页上的一些输入字段没有填写,所以我不得不不考虑这个条件。 即我没有填写开始日期,所以语句必须是
"SELECT * FROM Reports WHERE EndDate <= ? AND Performer = ?"
有3种不同的条件。那么,我是否必须编写 8 个不同的语句和 DAO 方法才能完成任务?真?也许还有其他解决方案?
编辑:我使用MySQL/
更改 SQL 以满足空值的需求。因为您还没有告诉我们您使用的是哪个数据库,所以我将使用"vanilla"SQL:
SELECT *
FROM Reports
WHERE (EndDate <= ? OR ? is null)
AND (Performer = ? OR ? is null)
每个参数传入两次。
另一种选择是根据参数为 null 更改 SQL(例如,从 where 子句中省略Performer = ?
),但这可能需要大量代码和测试。我会使用适应性强的 SQL,如果它表现不佳,那么尝试更高级的东西。
你不需要 8 个不同的语句。可以使用 if 语句生成查询。例如,
String query = "SELECT * FROM Reports where true";
if(startDate != null)
query = query + " and startDate <= ?";
if(endDate != null)
query = query + " and endDate <= ?";
if(performer != null)
query = query + " and performer = ?";
希望它对你有用。
No Prepare 语句不能单独排除 contion。为避免不必要的条件而构建的查询。
您可以使用以下代码生成 SQL:
StringBuilder whereClause = new StringBuilder();
String and = "";
if(EndDate == null || EndDate.length == 0)
{
whereClause.append(your condition);
and = " and";
}
if(StartDate == null || StartDate.length == 0)
{
whereClause.append(and).append(your condition);
and = " and";
}
if(Performer == null || Performer.length == 0)
{
whereClause.append(and).append(your condition);
}
并且根据您生成的查询,您需要将参数设置为预准备语句。