简体   繁体   中英

java.sql.SQLException: No value specified for parameter 4

I have here my code for inserting MCQ but when I click to submit it I'm getting an error while calling the method below

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

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

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

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

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

                st.addBatch(); 
            }

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

                st.addBatch();
            }

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

how to solve this problem

When st.addBatch() is executed, ALL parameters must be already set.

It's not the case in your code, since parameter #4 is not yet set in the first st.addBatch() when you are setting [multiple] parameters #3. You need to get those loops straight.

I believe you can just do the below:

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

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

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

            PreparedStatement st = cnx.prepareStatement(req);
            st.setString(1, question.getTitle());
            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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM