-2

可能重复:
如何在 JDBC 中获取插入 ID?

我试图获取最后一个插入 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?我的方法有什么问题?

4

1 回答 1

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.

于 2011-12-10T02:09:18.500 回答