Reputation: 121
I am getting this error when i try to execute this piece of code. When i remove the quotes of the question marks, then it says "You have an error in your SQL syntax;" Can somebody help me to get this fixed?
String query = "select date from ticket where date >='?' and date <= '?' ";
PreparedStatement pstmt1 = con.prepareStatement(query);
pstmt1.setString(1, fromdate);
pstmt1.setString(2, todate);
pstmt1.executeQuery(query);
Upvotes: 0
Views: 59
Reputation: 882686
Your actual error here is that you're executing the query string itself rather than the prepared statement:
pstmt1.executeQuery(query);
There is no executeQuery(String)
in the PreparedStatement
interface, instead it reverts to the one from the Statement
interface, which just runs the string, as-is, as a query. That means it will complain bitterly because ?
is not considered valid in that context.
You should just be using (including retrieving the result set):
ResultSet rs = pstmt1.executeQuery();
so the query execution is done in the prepared statement context rather than the statement context.
Upvotes: 2
Reputation: 1712
Do not enclose the placeholders with quotes
String query = "select date from ticket where date >='?' and date <= '?' ";
The java API will take care of adding quotes and adding escape sequences to the special characters, this should suffice:
String query = "select date from ticket where date >=? and date <= ? ";
Upvotes: 0