如何从表格中选择最后生成的ID

时间:2019-05-04 17:33:57

标签: java mysql java-ee

我想获取表体中最后插入的id,然后将其作为参数插入查询中(表体中的id是外键)。

这是插入检查的方法

public static void ajouter_examen(Examen ex) {
    Connection cnx;
    try {
        cnx = Connect.getConnection();
        String req = "insert into coordonnees_examen(date, classe, heure, matiere) values(?,?,?,?)";

        PreparedStatement st = cnx.prepareStatement(req);
        st.setString(1, ex.getDate());
        st.setObject(2, ex.getGroupe());
        st.setString(3, ex.getHeure());
        st.setObject(4, ex.getMatiere());

        st.executeUpdate();

    }

这将插入问题,我必须指出该问题属于哪项考试

public static void ajouter_question(Question question) {
        Connection cnx;
        try {

            cnx = Connect.getConnection();
            cnx.setAutoCommit(false);

            String req = "insert into question(titre, contenu, proposition, reponse) values(?,?,?,?)";

            PreparedStatement st = cnx.prepareStatement(req);
            st.setString(1, question.getTitre());
            st.setString(2, question.getContenu());

            for (Proposition prop : question.getListProp()) {
                st.setString(3, prop.getContenu());

                for (Correct corr : question.getReponse()) {
                    st.setString(4, corr.getCorrect());

                }

                st.addBatch();

                st.executeBatch();
                cnx.commit();

            }
        }

0 个答案:

没有答案