2012-11-29 66 views
1

我想使這個查詢:如何使用空日期進行SQL查詢?

Class.forName("org.postgresql.Driver"); 
    Connection conn= null; 
    conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgis","postgres","123456"); 
    PreparedStatement ps = null; 
    String sql = "SELECT num FROM parcels WHERE code_initial_right =(SELECT code_document FROM documents WHERE number_document=? or date_document='"+docd+"')"; 
    ps = conn.prepareStatement(sql); 
    ps.setString(1,docn); 
    ResultSet rs = ps.executeQuery(); 

docd可以等於null。當我嘗試這個我得到一個錯誤:

javax.servlet.ServletException: org.postgresql.util.PSQLException: ERROR: invalid input syntax for type date: "" 

我該怎麼辦呢?

+0

如何使用'if' 。 :) –

+0

如何追加或date_document ='「+ docd +」只有當字符串sql不爲null? – PbxMan

+0

你的意思是在'docd = null'指定docd到randomdate的情況下使用'if'嗎? –

回答

1

使用if

StringBuilder sql = new StringBuilder("SELECT num FROM parcels WHERE code_initial_right ="); 
if (docd != null) { 
    sql.append("(SELECT code_document FROM documents WHERE number_document=? or date_document='"+docd+"')"); 
}else { 
    sql.append("(SELECT code_document FROM documents WHERE number_document=?)"); 
} 
ps = conn.prepareStatement(sql.toString()); 
+0

是的,它的意志100%的作品。但我認爲我可以找到SQL或jdbc函數( –

3

使用IS NULL斷言:

.... 
OR docd IS NULL OR date_document = docd; 
+0

什麼意思'$ docd'中的'$'? –

+0

@KliverMax - 對不起,我使用'$'編寫'docd'來表明它是一個參數,你必須用Java以正確的方式編寫它。我編輯了我的答案。 –

+0

@ Mahmoud Gamal回答你的意思是'OR date_document IS NULL OR date_document = docd;'? Couse我得到錯誤:'錯誤:列「docd」不存在'。 –

1

嘗試ISNULL(date_document,default_date)是這樣的:

String sql = "SELECT num FROM parcels WHERE code_initial_right =(SELECT code_document FROM documents WHERE number_document=? or isnull(date_document, '"+docd+"') ='"+docd+"')"; 
+0

'錯誤:函數isnull(日期,未知)不存在' –

+0

@KliverMax ok,試試這個:String sql =「SELECT num FROM parcels WHERE code_initial_right =(SELECT code_document FROM documents WHERE number_document =?或NULLIF(date_document,'「+ docd +」')='「+ docd +」')「; –