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.
Apart from the basic compilation error (just remove
new), I spot 2 serious problems:Given the fact that
LIKEworks, yourmydatefield is apparently of avarchartype instead of a fullworthydate,datetimeortimestamptype. This is recipe for problems. You should always use the right data type for the information the field holds.%cannot be put after preparedstatement placeholder?. It has to be set in the value directly. However, this works withStringvalues only (and thusvarcharfield types). For a fullworthydate,datetimeandtimestamptype you’d rather use=,<,>orBETWEENinstead.There are 2 solutions:
Change the data type of the field to be a real
date,datetimeortimestamp, so that you can use the proper SQL syntax such asWHERE mydate BETWEEN ? AND ?.Use
preparedStatement.setString(1, "2000-01-13%")instead and remove those singlequotes around the placeholder?as well so that it ends likeWHERE mydate LIKE ?.See also: