【问题标题】:how to store two tables in sql using the foreign key in one jsp form如何在一个jsp表单中使用外键在sql中存储两个表
【发布时间】:2019-07-23 05:26:03
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 到目前为止你尝试过什么?你有什么问题?有代码吗?

标签: jsp servlets


【解决方案1】:
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");     
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2017-01-16
    • 2017-08-31
    • 1970-01-01
    相关资源
    最近更新 更多