无法在jdbc预处理语句中的外键表中插入数据

时间:2017-08-29 08:44:58

标签: mysql jdbc javabeans

我是新手。我有两张桌子。 registrationtablelogintable,其中registerationidregistrationtable中的主键,logintable中的外键registerationid Auto_Increment registrationtable。我可以在registrationtable中插入,但不能插入logintable。我正在使用PreparedStatement并拥有Bean课程。请任何人都可以帮助我。 提前感谢您的帮助。

try {               
        PreparedStatement preparedstatement=connection.prepareStatement("INSERT INTO registrationtable(firstname,lastname,dob,address,city,state,mob) VALUES (?,?,?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
        preparedstatement.setString(1,bean.getFirstName());
        preparedstatement.setString(2,bean.getLastName());
        preparedstatement.setString(3,bean.getDOB());
        preparedstatement.setString(4,bean.getAddress());
        preparedstatement.setString(5,bean.getCity());
        preparedstatement.setString(6,bean.getState());
        preparedstatement.setString(7,bean.getMobile());

        System.out.println("Dao Rgisteration : "+bean.getFirstName());
        preparedstatement.executeUpdate();

        ResultSet resultset=preparedstatement.getGeneratedKeys();
        resultset.next();
        int autoGeneratedKeyRegisteration = resultset.getInt(1);

        preparedstatement.close();
    //  resultset=preparedstatement.executeQuery("SELECT LAST_INSERT_ID() AS last_id FROM registerationtable");



        String sql="INSERT INTO logintable(registerationid,username,password) VALUES (LAST_INSERT_ID(),'xyz@gmail.com','xyzabc123')";
        PreparedStatement preparedstatement1=connection.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
        preparedstatement1.setInt(1,bean.getRegistrationId());
        preparedstatement1.setString(2, bean.getUsername());
        preparedstatement1.setString(3, bean.getPassword());
        System.out.println("Dao Login : "+bean.getUsername());
        preparedstatement1.executeUpdate();

        ResultSet resultset1=preparedstatement1.getGeneratedKeys();
        if(resultset1.next()){
        int autoGeneratedkeyLogin=resultset1.getInt(1);
        }
        resultset1=preparedstatement1.executeQuery("SELECT registerationid FROM logintable WHERE registerationid=LAST_INSERT_ID()");
        System.out.println(resultset);
        preparedstatement1.close();
    } catch(Exception e){e.getMessage();}finally{
        try{
            connection.close();
        }catch(Exception ex){ex.getMessage();}
    }

}

1 个答案:

答案 0 :(得分:0)

首先,我建议在事务中进行这些插入: https://stackoverflow.com/a/5723862/3323777

使用getGeneratedKeys代替LAST_INSERT_ID: https://stackoverflow.com/a/1915197/3323777

LAST_INSERT_ID有一些警告和限制: https://dba.stackexchange.com/a/21188