0

I am using jdbc to call a sql query ".... where mydate like '?%' " and I want to pass the parameter to the query with:

PreparedStatement ps;  
ps.setDate(1, new java.sql.Date.valueOf("2000-01-13"));

But this last line is not compiling, and I don't know why. When i enter the date directly into the query above, as in ".. where mydate like '2000-01-13%'", it works.

0

2 Answers 2

5

Apart from the basic compilation error (just remove new), I spot 2 serious problems:

  1. Given the fact that LIKE works, your mydate field is apparently of a varchar type instead of a fullworthy date, datetime or timestamp type. This is recipe for problems. You should always use the right data type for the information the field holds.

  2. % cannot be put after preparedstatement placeholder ?. It has to be set in the value directly. However, this works with String values only (and thus varchar field types). For a fullworthy date, datetime and timestamp type you'd rather use =, <, > or BETWEEN instead.

There are 2 solutions:

  1. Change the data type of the field to be a real date, datetime or timestamp, so that you can use the proper SQL syntax such as WHERE mydate BETWEEN ? AND ?.

  2. Use preparedStatement.setString(1, "2000-01-13%") instead and remove those singlequotes around the placeholder ? as well so that it ends like WHERE mydate LIKE ?.

See also:

Sign up to request clarification or add additional context in comments.

2 Comments

+1 I was about to recommend BETWEEN since it's clear what they're trying to do
Thanks for catching that, both problems were existing and now solved. Thanks!
1

You'll want to use:

java.sql.Date.valueOf("2000-01-13")

That is, do not use new in front of it. By using new, you are telling the compiler you want to create a new object. Since valueOf is a static method, you do not need to create an object in order to call it.

Regardless, the reason it does not compile is because new java.sql.Date.valueOf("str") is not a valid statement. You would have to say new java.sql.Date() with parentheses if you wanted to create a new instance of Date, which you do, but by a different means.

1 Comment

Thanks, apparently my sql database's so-called date was using a varchar as BalusC explained below.

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.