无法使用executeQuery()发出数据操作语句

时间:2009-12-15 06:44:39

标签: java mysql jdbc

在MySQL中,我有两个表,tableAtableB。我正在尝试执行两个查询:

executeQuery(query1) 
executeQuery(query2)

但是我收到以下错误:

can not issue data manipulation statements with executeQuery().

这是什么意思?

10 个答案:

答案 0 :(得分:161)

要操纵您实际需要的数据executeUpdate()而不是executeQuery()

以下是来自executeUpdate() javadoc的摘录,该摘录本身就是一个答案:

  

执行给定的SQL语句,该语句可以是INSERT,UPDATE或DELETE语句,也可以是不返回任何内容的SQL语句,例如SQL DDL语句。

答案 1 :(得分:18)

执行DML语句时,您应使用executeUpdate / execute而不是executeQuery

以下是简要比较:

executeQueryVSexecuteUpdateVSexecute

答案 2 :(得分:15)

使用executeUpdate()发布数据操作语句。 executeQuery()仅适用于SELECT查询(即返回结果集的查询)。

答案 3 :(得分:5)

这就是executeUpdate的用途。

以下是差异的简短摘要:http://www.coderanch.com/t/301594/JDBC/java/Difference-between-execute-executeQuery-executeUpdate

答案 4 :(得分:4)

对于删除查询-在@Modifying之前使用@Transactional@Query,例如:-

@Repository
public interface CopyRepository extends JpaRepository<Copy, Integer> {

    @Modifying
    @Transactional
    @Query(value = "DELETE FROM tbl_copy where trade_id = ?1 ; ", nativeQuery = true)
    void deleteCopyByTradeId(Integer id);

}

它不会出现java.sql.SQLException: Can not issue data manipulation statements with executeQuery()错误。

答案 5 :(得分:3)

ExecuteQuery需要一个结果集。我不熟悉Java / MySQL,但是要创建索引,你可能需要一个ExecuteUpdate()。

答案 6 :(得分:3)

这段代码对我有用:我设置了一个INSERT值,并获得了该值的LAST_INSERT_ID(),这是一个SELECT;我使用java NetBeans 8.1,MySql和java.JDBC.driver

-----------------------------------------
buyer    itemX   itemY   sum of bid 
---------------------------------‌​-------- 
buyer13  item1   item2     350 
buyer2   item1   item2     283 
buyer65  item1   item2     236         
buyer602 item3   item4     80 
buyer703 item3   item4     76 
buyer640 item3   item4     69 

答案 7 :(得分:3)

@Modifying
@Transactional
@Query(value = "delete from cart_item where cart_cart_id=:cart", nativeQuery = true)
public void deleteByCart(@Param("cart") int cart); 

不要忘记在@query之前添加@Modifying和@Transnational。它对我有用。

要使用JPA原生查询删除某些条件下的记录,上述注释很重要。

答案 8 :(得分:1)

如果您使用的是Spring Boot,只需添加一个@Modifying注释。

@Modifying
@Query
(value = "UPDATE user SET middleName = 'Mudd' WHERE id = 1", nativeQuery = true)
void updateMiddleName();

答案 9 :(得分:-1)

除了括号中的executeUpdate()之外,还必须添加一个变量来使用SQL语句。

例如:

PreparedStatement pst =  connection.prepareStatement(sql);
int numRowsChanged = pst.executeUpdate(sql);
相关问题