1

I want to make this query:

    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();

But docd can be equals null. When i try this i get an error:

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

What can i do with this?

3
  • How about using if. :) Commented Nov 29, 2012 at 9:44
  • How appending or date_document='"+docd+" to String sql only when is not null? Commented Nov 29, 2012 at 9:46
  • You mean use if in case when docd=null assign docd to randomdate? Commented Nov 29, 2012 at 9:47

3 Answers 3

3

Use the IS NULL predicate:

....
OR docd IS NULL OR date_document = docd;
Sign up to request clarification or add additional context in comments.

3 Comments

@KliverMax - Sorry, I write docd with $ to indicate that it is a parameter, you have to write it with the proper way with Java. I edited my answer.
@ Mahmoud Gamal in answer you mean OR date_document IS NULL OR date_document = docd;? Couse i get error: ERROR: column "docd" does not exist.
But if i use OR date_document IS NULL OR date_document = docd; i get erorr: ERROR: invalid input syntax for type date: ""
1

Using 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());

1 Comment

Yeah its will 100% works. But i thought that i can find something in SQL or jdbc functions(
1

try ISNULL(date_document, default_date) like this:

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

2 Comments

ERROR: function isnull(date, unknown) does not exist
@KliverMax ok, try this: String sql = "SELECT num FROM parcels WHERE code_initial_right =(SELECT code_document FROM documents WHERE number_document=? or NULLIF(date_document, '"+docd+"') ='"+docd+"')";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.