Java 参数索引超出范围(4>;参数数,即2)

Java 参数索引超出范围(4>;参数数,即2),java,mysql,sql,jdbc,Java,Mysql,Sql,Jdbc,我正在制作一个简单的JavaJDBC程序,在这个程序中,我必须在表中插入一个用户历史记录,但在表中有库存。这是我的密码 public void insertIntoHistory(ArrayList<QuestionAnswer> questionAnswer) throws Exception { try { conn.setAutoCommit(false); int maxId = getMaxSets() + 1; f

我正在制作一个简单的JavaJDBC程序,在这个程序中,我必须在表中插入一个用户历史记录,但在表中有库存。这是我的密码

public void insertIntoHistory(ArrayList<QuestionAnswer> questionAnswer) throws Exception {
    try {
        conn.setAutoCommit(false);
        int maxId = getMaxSets() + 1;

        for (QuestionAnswer qa : questionAnswer) {
            String getSql = "INSERT INTO userhist(id, questionid, "
                    + "givenanswerid, isCorrect, questionSet) "
                    + "VALUES (NULL,?,?,?,?)";

            pst = conn.prepareStatement(getSql);
            pst.setInt(1, qa.getQuestionId());
            pst.setInt(2, qa.getAnswerId());
            pst.setBoolean(3, (isCorrect(qa.getQuestionId(), qa.getAnswerId())));
            pst.setInt(4, maxId);

            pst.executeUpdate();
        }

        conn.commit();
    } catch (SQLException e) {
        System.out.println(e.getMessage());
        conn.rollback();
        throw e;
    }
}
这是我的桌子结构


此处发生的情况请帮助我

问题可能是因为您试图在
id
列中插入
NULL
。由于它是自动递增非空的,因此在执行
INSERT
命令时,应该假装它不存在

可能是@Yserbius的复制品没有解决我的问题,请你看看,可能我们有这种奇怪的行为,因为普遍的不一致性。1.请在循环之前创建一次准备好的语句,然后在循环中进行设置和执行。此外,您还必须在执行后关闭语句(考虑
try(…){…}
)。2.另一个问题,您确定异常来自此方法,而不是来自
getMaxSets()
?您使用的是什么数据库?您还可以发布您的模式吗?它看起来像是一个字段,您可能会通过对同一对象的并发访问来覆盖它。您通常应该尝试将对JDBC类型的引用保留在方法的局部变量中,否则必须确保使用唯一字段,或者正确地同步访问。但是,为了确保我们需要看到一个。我通过在
isCorrect
方法中创建PrepareStatement的新实例解决了这个问题。谢谢你的回复
private boolean isCorrect(int questionId, int ansId) throws SQLException {
    String sql = "SELECT COUNT(*) AS Total FROM correctanswer where questionid = ? and answerid = ?";
    boolean isCorrect = false;

    try {
        pst = conn.prepareStatement(sql);
        pst.setInt(1, questionId);
        pst.setInt(2, ansId);

        ResultSet res = pst.executeQuery();
        int count = 0;
        if (res.next()) {
            count = res.getInt(1);
        }

        isCorrect = count > 1;

    } catch (SQLException e) {
        System.out.println(e.getMessage());
        throw e;
    }

    return isCorrect;
}