-2

Possible Duplicate:
How to get the insert ID in JDBC?

I was trying to get the last insert ID, but apparently it's not working, it keeps on giving me a bunch of errors one of them is this

java.sql.SQLException: Can not issue SELECT via executeUpdate().

I was trying to get the last Inserted it but it doesn't work, here's my code

public int getLastInsertID(){
        try{
        Statement statement =  conn.createStatement();
        ResultSet rs = null;
        statement.executeUpdate("SELECT LAST_INSERTED_ID", Statement.RETURN_GENERATED_KEYS);
        rs = statement.getGeneratedKeys();
        while(rs.next()){
            System.out.println(""+rs.getInt(1));
            id =    rs.getInt(1);
            JOptionPane.showMessageDialog(null,id);

        }

        }catch(Exception e){
            e.printStackTrace();
        }

        return id;
    }
}

and the second one is

public void addEmployee(Personal p ,Contact c,Employee e) {
        Statement statement = null;

        String insert0 = "INSERT INTO `finalpayroll`.`users` (`emp_id`, `emp_pass`) VALUES ('2010-010122', '1231922')";
        try{
            statement = conn.createStatement();
            statement.executeUpdate(insert0);
            statement.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        id = getLastInsertID();

        String insert1 = "INSERT INTO personal_info (`idpersonal_info`,`First_Name`, `Middle_Initial`, `Last_Name`, `Date_Of_Birth`, `Marital_Status`, `Beneficiaries`) VALUES ("+id+",'"+p.getFirstName()+"', '"+p.getMiddleInitial()+"'" +
                "       , '"+p.getLastName()+"', '"+p.getDateOfBirth()+"', '"+p.getMaritalStatus()+"', '"+p.getBeneficiaries()+"')";
        try{
            statement = conn.createStatement();

        statement.executeUpdate(insert1);
        statement.close();
        conn.close();
        JOptionPane.showMessageDialog(null, "Employee Added!!");
        }catch(Exception ex){
            ex.printStackTrace();
        }


    }

how could I get the last inserted id? what's wrong wit my method?

Community
  • 1
  • 1
user962206
  • 15,637
  • 61
  • 177
  • 270

1 Answers1

0

Looks like it may be a bug with certain versions of the mysql driver. Search this source code for the error message. They aren't checking for the getGeneratedIds condition.

MySQL has a similar 'won't fix' bug open since 2005. The discussion mentions that it's not a requirement of the JDBC API that their driver support the feature. Seems likely this is a known and unaddressed issue.

Chip McCormick
  • 744
  • 4
  • 17