0

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);
6
  • You don't quote parameters, just use where date >= ? and date <= ? Commented Mar 23, 2015 at 5:46
  • I removed quotes and them it says You have an error in your SQL syntax Commented Mar 23, 2015 at 5:47
  • What's the error? Also, have you seen the BETWEEN clause, eg WHERE date BETWEEN ? AND ? Commented Mar 23, 2015 at 5:47
  • check the manual that corresponds to your MySQL server version for the right syntax to use near '? and date <=?' at line 1 Commented Mar 23, 2015 at 5:50
  • Update your question with the current code. Don't type it, copy and paste Commented Mar 23, 2015 at 5:51

3 Answers 3

2

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.

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

1 Comment

date is a valid column name that doesn't need identifier quotes. See the list under this table - dev.mysql.com/doc/refman/5.5/en/…
0

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 <= ?  ";

Comments

0

setString(...) --> setDate(...)

Comments

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.