1

我想做这个查询:

    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: ""

我能用这个做什么?

4

3 回答 3

3

使用IS NULL谓词:

....
OR docd IS NULL OR date_document = docd;
于 2012-11-29T09:42:42.970 回答
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());
于 2012-11-29T09:54:34.053 回答
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+"')";
于 2012-11-29T09:55:45.747 回答