首页 > 解决方案 > 如何在一个jsp表单中使用外键在sql中存储两个表

问题描述

单击按钮时如何将数据存储在两个不同的表中。

假设我有一个名为 team1 和 team2 的 2 个表。

在表 team1 中有 2 个字段 teamid,teamname

在表 team2 中有 3 个字段 team2id,team2name,teamid 这里 teamid 是外键。

因此,当我单击插入按钮时,所有数据都将插入到相应的表中

标签: jspservlets

解决方案


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");     
    }

推荐阅读