0

I am trying to write my simple pet project using JDBC

Here is my prepared statement:

String query = "SELECT c.id as categoryId, c.`name`, p.id as productId, p.title, p.price, p.`status` FROM product p " +
                "JOIN product_categories pc ON p.id = pc.product_id " +
                "JOIN category c ON pc.category_id = c.id " +
                "JOIN shop s ON c.shop_id = s.id " +
                "WHERE s.`name` = ?";
        PreparedStatement preparedStatement = conn.prepareStatement(query);
        preparedStatement.setString(1, shop.getName());
        preparedStatement.executeQuery(query);

However, I am getting every time this:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1

What am i doing wrong?

quento
  • 1,074
  • 4
  • 20
  • 43

1 Answers1

4

Remove the query string which has already been specified in the statement

preparedStatement.executeQuery();

Statement.executeQuery(query) is intended only for non-prepared Statements where no parameter substitution is performed producing the error shown

Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Clarification: `executeQuery(query)` is a method inherited from `Statement` executing the given `query` as-is. `executeQuery()` is a method from `PreparedStatement` executing the statement that was supplied on the `prepareStatement(query)` call, substituting `?` markers with the values supplied by `setXxx()` calls. – Andreas Feb 21 '16 at 13:56
  • @Andreas conversely no placeholder substitution is performed using `Statement.executeQuery(query)` producing the error shown :) – Reimeus Feb 21 '16 at 14:13
  • Yup, hence the "as-is" in my comment. Suggestion: Add clarification to answer. Change wording as needed. ;-) – Andreas Feb 21 '16 at 14:14