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

sil*_*kid 88 java mysql jdbc

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

executeQuery(query1) 
executeQuery(query2)
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

can not issue data manipulation statements with executeQuery().
Run Code Online (Sandbox Code Playgroud)

这是什么意思?

Bal*_*usC 170

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

这是executeUpdate()javadoc 的摘录,它本身就是一个答案:

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


Nit*_*nda 26

对于删除查询 - 使用@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);

}
Run Code Online (Sandbox Code Playgroud)

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

编辑:

由于这个答案得到了很多人的支持,我也会让你参考文档以获得更多的理解。

@交易

By default, CRUD methods on repository instances are transactional. For read operations, 
the transaction configuration readOnly flag is set to true. 
All others are configured with a plain @Transactional so that default transaction 
configuration applies.
Run Code Online (Sandbox Code Playgroud)

@修改

Indicates a query method should be considered as modifying query as that changes the way 
it needs to be executed. This annotation is only considered if used on query methods defined 
through a Query annotation). It's not applied on custom implementation methods or queries 
derived from the method name as they already have control over the underlying data access 
APIs or specify if they are modifying by their name.

Queries that require a @Modifying annotation include INSERT, UPDATE, DELETE, and DDL 
statements.
Run Code Online (Sandbox Code Playgroud)


Jas*_*key 25

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

这是一个简短的比较:

executeQueryVSexecuteUpdateVSexecute


OMG*_*ies 15

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


For*_*est 7

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

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

  • 对于 spring boot 存储库中的删除语句@Transactional 会有所帮助 (3认同)
  • https://codar.club/blogs/5cd7f06bec80a.html 解释了修改、事务和查询注释的用法。我使用以下方法解决了我的问题:``@Modifying(clearAutomatically = true) @Transactional`` 位于定义删除查询的 @Query 注释上方 (2认同)

小智 6

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

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

要使用 JPA 的本机查询删除具有某些条件的记录,上述注释非常重要。