[java] Cannot issue data manipulation statements with executeQuery()

In MySQL I have two tables, tableA and tableB. I am trying to execute two queries:

executeQuery(query1) 
executeQuery(query2)

But I get the following error:

can not issue data manipulation statements with executeQuery().

What does this mean?

This question is related to java mysql jdbc

The answer is


executeQuery() returns a ResultSet. I'm not as familiar with Java/MySQL, but to create indexes you probably want a executeUpdate().


When executing DML statement , you should use executeUpdate/execute rather than executeQuery.

Here is a brief comparison :

executeQueryVSexecuteUpdateVSexecute


If you're using spring boot, just add an @Modifying annotation.

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

Besides executeUpdate() on the parentheses, you must also add a variable to use an SQL statement.

For example:

PreparedStatement pst =  connection.prepareStatement(sql);
int numRowsChanged = pst.executeUpdate(sql);

Use executeUpdate() to issue data manipulation statements. executeQuery() is only meant for SELECT queries (i.e. queries that return a result set).


That's what executeUpdate is for.

Here's a very brief summary of the difference: http://www.coderanch.com/t/301594/JDBC/java/Difference-between-execute-executeQuery-executeUpdate


This code works for me: I set values whit an INSERT and get the LAST_INSERT_ID() of this value whit a SELECT; I use java NetBeans 8.1, MySql and java.JDBC.driver

                try {

        String Query = "INSERT INTO `stock`(`stock`, `min_stock`,   
                `id_stock`) VALUES ("

                + "\"" + p.get_Stock().getStock() + "\", "
                + "\"" + p.get_Stock().getStockMinimo() + "\","
                + "" + "null" + ")";

        Statement st = miConexion.createStatement();
        st.executeUpdate(Query);

        java.sql.ResultSet rs;
        rs = st.executeQuery("Select LAST_INSERT_ID() from stock limit 1");                
        rs.next(); //para posicionar el puntero en la primer fila
        ultimo_id = rs.getInt("LAST_INSERT_ID()");
        } catch (SqlException ex) { ex.printTrace;}

For Delete query - Use @Modifying and @Transactional before the @Query like:-

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

}

It won't give the java.sql.SQLException: Can not issue data manipulation statements with executeQuery() error.

Edit:

Since this answer is getting many upvotes, I shall refer you to the documentation as well for more understanding.

@Transactional

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.

@Modifying

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.

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

Do not forget to add @Modifying and @Transnational before @query. it works for me.

To delete the record with some condition using native query with JPA the above mentioned annotations are important.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to jdbc

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' Hibernate Error executing DDL via JDBC Statement Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] MySQL JDBC Driver 5.1.33 - Time Zone Issue Spring-Boot: How do I set JDBC pool properties like maximum number of connections? Where can I download mysql jdbc jar from? Print the data in ResultSet along with column names How to set up datasource with Spring for HikariCP? java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why? java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname