2016-02-21 66 views
0

我想写使用JDBC的PreparedStatement的JDBC:值插入

这是我事先准备好的声明我简单的宠物项目:

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); 

但是,我得到的每一次这样的:

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 

我在做什么错?

回答

4

删除已经被在声明

preparedStatement.executeQuery(); 

Statement.executeQuery(query)指定的查询串仅用于非制备Statements其中生产所示

+0

澄清的错误不进行参数替换:'的executeQuery(查询)'是一个从'Statement'继承的方法,按原样执行给定的'query'。 'executeQuery()'是'PreparedStatement'执行'prepareStatement(query)'调用提供的语句的一种方法,用'setXxx()'调用提供的值替换'?'标记。 – Andreas

+0

@Andreas反过来,没有占位符替换使用'Statement.executeQuery(query)'执行,产生显示的错误:) – Reimeus

+0

是的,因此我的评论中的“原样”。建议:加上澄清回答。根据需要更改措辞。 ;-) – Andreas

相关问题