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?