如何在一个jsp表单中使用外键在sql中存储两个表
单击按钮时如何将数据存储在两个不同的表中 假设我有两个表,分别命名为team1和team2 在表team1中,有两个字段teamid、teamname 在表team2中,有3个字段team2id、team2name、teamid,其中teamid是外键如何在一个jsp表单中使用外键在sql中存储两个表,jsp,servlets,Jsp,Servlets,单击按钮时如何将数据存储在两个不同的表中 假设我有两个表,分别命名为team1和team2 在表team1中,有两个字段teamid、teamname 在表team2中,有3个字段team2id、team2name、teamid,其中teamid是外键 因此,当我单击“插入”按钮时,所有数据都将插入到相应的表中到目前为止您尝试了什么?你有什么问题?有密码吗? Use separate insert into table and get id and insert another table.
因此,当我单击“插入”按钮时,所有数据都将插入到相应的表中到目前为止您尝试了什么?你有什么问题?有密码吗?
Use separate insert into table and get id and insert another table.
public int saveTeamInfo(String teamname){
int teamid = 0; //initialize
PreparedStatement pst = conn.prepareStatement("INSERT INTO team(teamname) VALUES(?);", Statement.RETURN_GENERATED_KEYS);
pst.setString(1, teamname);
pst.executeUpdate();
//now get the teamid
ResultSet rs = pst.getGeneratedKeys();
while (rs.next()) {
teamid = rs.getInt(1); //get the id of the inserted event
}
return teamid; //return the teamid
}
public void saveTeam2Info(int teamid, String team2name){
PreparedStatement pst = conn.prepareStatement("INSERT INTO team2 (team2name, teamid )VALUES(?, ?, ?, ?);");
pst.setInt(1, team2name);
pst.setString(2, teamid);
pst.executeUpdate();
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
//get our parameters
String teamname = request.getParameter("teamname");
String team2name = request.getParameter("team2name");
//insert into team table and return teamid
int teamid = eas.saveTeamInfo(teamname);
//use teamid and insert into team2 table
eas.saveTeam2Info(teamid,team2name);
//all done
response.sendRedirect("/viewS.jsp");
}