Question

I'm a complete novice in Java programming but I'm hammering away. I have searched extensively but I can't figure it out even though many fellow beginner programmers have had the same problem..

I have is this Java <> MySQL problem, and I can't wrap my head around it!

If I execute this query in phpMyAdmin:

SET count = 0; UPDATE tablename SET table_id = count:= count + 1;  
ALTER TABLE tablename AUTO_INCREMENT = 1;

It works as I want it to, reset ID (after I delete a row) it may not be the most elegant solutions but it gets the job done.

But as soon as I execute the same query from eclipse my console lights up like a Christmas tree and I get a:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE tablename SET table_id = @count:= @count + 1; ALTER TABLE tablename AU' at line 1

Error... check my syntax. It works in phpMyAdmin. My Eclipse Java method:

public void resetDBID(){
    try{
        // query to reset menu_id manly after delete row
        Statement statement = con.connection.createStatement();
        String sset;
        sset =  "SET @count = 0; "
                + "UPDATE afhaalmenus SET menu_id = @count:= @count + 1; "
                + "ALTER TABLE afhaalmenus AUTO_INCREMENT = 1;";

        statement.execute(sset);

    } catch(SQLException ex){
        String message = "rest ID fail";
        JOptionPane.showMessageDialog(null, message, "method fail", JOptionPane.INFORMATION_MESSAGE);
        ex.printStackTrace();
    }
}

What is it that I'm missing here? Or doing wrong... Thanks in advance for all of your help!

Was it helpful?

Solution

You can use addBatch

String s1 = "SET @count = 0";
String s2 = ...

try {
// query to reset menu_id manly after delete row
     connection = database.getConnection();
     Statement statement = connection.createStatement();
     statement.addBatch(s1);
     statement.addBatch(s2);    
     statement.addBatch(s2);   
     s.executeBatch();
     connection.commit();
} catch (SQLException e) {
    connection.rollback();
    throw e;
} finally {
    close(statement);
    close(connection);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top