124

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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
silverkid
  • 9,291
  • 22
  • 66
  • 92
  • Do you have any access to MySQL other than via JDBC - MySQL Administrator? Or command line? – OMG Ponies Dec 15 '09 at 06:46
  • i have the access to mysql admin. however the requiement is such that . the mysql database will be created, modified , updated, etc. using mysql admin but after that all operations are required to be done with java. – silverkid Dec 15 '09 at 06:52
  • Better to include the index creation in scripts to create the database than via JDBC, likely after you could have already used them. – OMG Ponies Dec 15 '09 at 06:56

11 Answers11

223

To manipulate data you actually need executeUpdate() rather than executeQuery().

Here's an extract from the executeUpdate() javadoc which is already an answer at its own:

Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
55

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

Here is a brief comparison :

executeQueryVSexecuteUpdateVSexecute

JaskeyLam
  • 15,405
  • 21
  • 114
  • 149
48

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();
Forrest
  • 2,968
  • 1
  • 27
  • 18
  • 3
    for delete statement in spring boot repository @Transactional will help – aac Jun 19 '19 at 11:53
  • 2
    https://codar.club/blogs/5cd7f06bec80a.html explains the usage of modifying, transactional and query annotations. I resolved my problem using: ``@Modifying(clearAutomatically = true) @Transactional`` just above the @Query annotation defining my delete query – user666 Aug 26 '19 at 10:58
  • Exactly what i wanted – Deviprasad Sharma Mar 08 '21 at 11:54
33

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.
Nitin Nanda
  • 805
  • 2
  • 11
  • 27
17

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

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
6
@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.

BeUndead
  • 3,463
  • 2
  • 17
  • 21
Sunil
  • 61
  • 1
  • 2
5

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

Carl Smotricz
  • 66,391
  • 18
  • 125
  • 167
4

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;}
Mati
  • 66
  • 1
3

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

n8bar
  • 531
  • 1
  • 7
  • 25
Neil N
  • 24,862
  • 16
  • 85
  • 145
0
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java_swing_db", "root", "root");

Statement smt = conn.createStatement();

String sql = "SELECT * FROM `users` WHERE `email` = " + email + " AND `password` = " + password + " LIMIT 1;";

String registerSql = "INSERT INTO `users`(`email`, `password`, `name`) VALUES ('" + email + "','" + password + "','" + name + "')";

System.out.println("SQL: " + registerSql);
            
int result = smt.executeUpdate(registerSql);
System.out.println("Result: " + result);

if (result == 0) {
   JOptionPane.showMessageDialog(this, "This is alredy exist");
} else {
  JOptionPane.showMessageDialog(this, "Welcome, Your account is sucessfully created");
  App.isLogin = true;
  this.dispose();
  new HomeFrame().show();
}
conn.close();
-2

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);
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
veloz
  • 9
  • Hello! As a heads up, questions and answers on Stack Overflow must be written in English (else they run the risk of deletion and/or Google Translation). Cheers! (_Hola! Como las cabezas para arriba, las preguntas y respuestas sobre Stack Overflow debe estar escrito en Inglés (de lo contrario corren el riesgo de eliminación y / o Google Traductor). ¡Salud!_) – Chris Forrence Mar 23 '15 at 21:54