Cannot issue data manipulation statements with exe

2019-01-01 16:27发布

问题:

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?

回答1:

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.



回答2:

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



回答3:

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

Here is a brief comparison :

\"executeQueryVSexecuteUpdateVSexecute\"



回答4:

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



回答5:

ExecuteQuery expects a result set. I\'m not as familiar with Java/MySQL, but to create indexes you probably want a ExecuteUpdate().



回答6:

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


回答7:

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


标签: java mysql jdbc