2017-08-25 88 views
0

我有2 datebox做一個過濾器。他們的價值將決定我的查詢中的'from'和'to'(我現在使用Oracle),這裏是代碼。如何使過濾器之間的兩個datebox ZK

@Listen("onClick=#btnSaveFilter") 
public void saveFilter() throws Exception { 
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 

    c_main_filter.detach(); 
    cc.refreshFilter("" 
      +"[Date of Birth] between '" + formatter.format(dbDateBirthFrom.getValue()).toString() + "' " 
      + "and '" + formatter.format(dbDateBirthto.getValue()).toString() + "'"); 

} 

當兩個datebox都有值時,查詢工作。但是當他們沒有價值時,查詢就不會提供任何數據。

時datebox具有價值,它給數據

"[Registration Date] between '2010-09-23' and '2010-09-23' " 

時datebox沒有價值,它沒有給出數據

"[Registration Date] between '' and '' " 

像另一個過濾器我預計,如果該值「然後」所有數據都會顯示,但不會顯示:D haha​​ha。實際情況比這個要多,過濾器有很多參數其中之一就是這個條件,有的使用日期格式,所以會有更多這樣的條件。

你知道如何優雅地解決這個問題,我一直在考慮用'if'來確定datebox有沒有值或沒有,那麼我會追加文本來查詢文本,如果他們兩個都有值,我發現了另一個問題,我怎麼能在查詢添加「和」給另一個條件,

讓的說我有5個條件,然後

"select * from xxxx where 1stcondition and 2ndcondition and 
3rdcondition and 4thcondition and 5th condition" 

所以當5thcondition的dateboxes沒有價值的查詢將錯這樣

"select * from xxxx where 1stcondition and 2ndcondition and 
3rdcondition and 4thcondition and" 

如果我想用'if'我該怎麼玩'和'?但如果你有替代這將是偉大的事業,我沒有對付「如果」:d

回答

1

您可以使用String.isEmpty(),以確定是否需要把and

String where = ""; 

if (from != null && to != null) { 
    where += <yourDateCondition>; 
} 

if (<needToAddSecondCondtion>) { 
    if (!where.isEmpty()) { 
     where += " and "; 
    } 
    where += <secondCondition>; 
} 

// continue with other conditions 

String query = "select * from xxxx where " + where; 
+0

uuuh,我給一個嘗試 – ikiSiTamvaaan

+0

wihiiii感謝它的工作:d – ikiSiTamvaaan

0

我不知道,如果你使用普通的JDBC或ORM框架如Hibernate查詢到的數據庫,但你可以嘗試這樣的事:

public void saveFileter(){ 
StringBuilder sb = new StringBuilder(); 
sb.append("select * from table "); 

if(dbDateBirthFrom.getValue() != null{ 
    sb.append(determineFilterWord(sb.toString())); 
    sb.append("your condition "); 
} 

if(dbDateBirthTo.getValue() != null{ 
    sb.append(determineFilterWord(sb.toString())); 
    sb.append("your condition ") 
} 
session.createQuery(sb.toString()); //if you using hibernate 
} 

private string determineFilterWord(String query){ 
    if(query.toLowerCase().indexOf("where") != -1){ 
    return "and "; 
    }else{ 
    return "where "; 
    } 
} 
+0

是的,我想以同樣的方式,但什麼「和」東西兄弟?如果條件不匹配字符串不會追加的情況,並查詢將例如被打破的「SELECT * FROM XXXX,其中1stcondition和2ndcondition和 3rdcondition和4thcondition和」 – ikiSiTamvaaan

+0

@ikiSiTamvaaan從wkwk地檢查我的更新答案,順便說一句? –

+0

你有一個很好的代碼在那裏,query.toLowerCase()的indexOf(「何處」)!= -1是檢查自己是否有字或地方不是在我的查詢字符串嗎?我會upvote你的答案,如果我可以爲此代碼,但但我還不能T.T ....我?從kufuki土地哈哈哈哈IM:d – ikiSiTamvaaan

相關問題