我试图获取最后一个插入ID,但显然它不起作用,它继续给我一堆错误,其中一个就是这个
java.sql.SQLException: Can not issue SELECT via executeUpdate().
我试图获得最后一次插入但它不起作用,这是我的代码
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;
}
}
,第二个是
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();
}
}
我怎样才能获得最后插入的ID?我的方法有什么问题?