我是新手。我有两张桌子。 registrationtable
和logintable
,其中registerationid
是registrationtable
中的主键,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();}
}
}
答案 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