jsp - 如何在一个jsp表单中使用外键在sql中存储两个表
问题描述
单击按钮时如何将数据存储在两个不同的表中。
假设我有一个名为 team1 和 team2 的 2 个表。
在表 team1 中有 2 个字段 teamid,teamname
在表 team2 中有 3 个字段 team2id,team2name,teamid 这里 teamid 是外键。
因此,当我单击插入按钮时,所有数据都将插入到相应的表中
解决方案
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");
}
推荐阅读
- python - df.set_index() 在数据框单元格中生成奇怪的对象
- java - CountDownTimer 和 textView - 未正确显示时间
- javascript - 使用 D3.js 时,如何在热图顶部添加文本以正确显示每个矩形的值?
- java - 所需类型不匹配转换为所需类型在 springboot kotlin 应用程序中失败
- javascript - 为什么我的 Firestore 请求没有得到任何回复?
- constraints - 这个线性规划问题的约束是什么?
- python - 问题将 2 个输入拟合到我的 keras 模型
- css - 为什么我没有在 React Native 中获得神经拟态设计?
- c# - ADOMD.NET 中的连接 - 轮询连接状态
- webpack - Webpack - 图像未正确加载