我想在一个表中插入记录,同时我想更新另一个表中的记录。为此,如果任何一个查询失败,我想使用事务,那么所有查询都会回滚。为此,我正在使用批处理...步骤如下
首先,我设置AutoCommit(false)
为连接 obj。
然后dmlPreparedStatement = dbConnection.prepareStatement(Insertquery);
- 设置参数为
dmlPreparedStatement
dmlPreparedStatement.addBatch();
在此之后,我想为此UPDATE
批量添加查询-
dmlPreparedStatement = dbConnection.prepareStatement(Updatequery);
相同的 PreparedStatement 对象,但具有新的更新查询- 设置参数为
dmlPreparedStatement
dmlPreparedStatement.addBatch();
当dmlPreparedStatement.executeBatch();
完成时它只执行更新语句插入操作未完成。
他们是否有任何方式将相同的 PreparedStatement 对象用于多个差异。查询。
尝试块中的代码
String query="INSERT INTO CANDIDATEANSWER " +
"(CANDIDATEEXAMITEMID,FKCANDIDATEID,FKITEMID,OPTIONID,ATTEMPTEDTIME,ISCORRECT) " +
"VALUES (?,?,?,?,?,?)";
dbConnection = icrudCandidate.getConnection();
dbConnection.setAutoCommit(false);
dmlPreparedStatement = dbConnection.prepareStatement(query);
for (CandidateAnswer candidateAnswer : candidateItemAssociation.getCandidateAnswers()) {
if(candidateAnswer.getOptionID() != 0)
{
dmlPreparedStatement.setLong(1, candidateAnswer.getCandidateExamItemID());
dmlPreparedStatement.setLong(2, candidateAnswer.getFkcandidateID());
dmlPreparedStatement.setLong(3, candidateAnswer.getFkItemID());
dmlPreparedStatement.setLong(4, candidateAnswer.getOptionID());
java.util.Date dt = new java.util.Date();
dmlPreparedStatement.setObject(5, dt,java.sql.Types.TIMESTAMP,java.sql.Types.TIMESTAMP);
String sql = "SELECT ISCORRECT FROM ITEMOPTION IO WHERE IO.OPTIONID="+candidateAnswer.getOptionID();
preparedStatement = dbConnection.prepareStatement(query);
resultSet = preparedStatement.executeQuery(sql);
while(resultSet.next())
{
if(resultSet.getBoolean("ISCORRECT"))
{
dmlPreparedStatement.setBoolean(6, true);
}
else
{
isCorrect=false;
dmlPreparedStatement.setBoolean(6, false);
}
}
resultSet.close();
}
dmlPreparedStatement.addBatch();
}
query="UPDATE CANDIDATEITEMASSOCIATION SET ISCORRECT=?,MARKSOBTAINED=? WHERE CANDIDATEEXAMITEMID="+candidateItemAssociation.getCandidateAnswers().get(0).getCandidateExamItemID();
PreparedStatement dmlPreparedStatement1 = dbConnection.prepareStatement(query);
dmlPreparedStatement1.setBoolean(1, isCorrect);
if(isCorrect)
{
dmlPreparedStatement1.setString(2, String.valueOf(getPerItemMarksByPaperId(paperId)));
}
else
{
dmlPreparedStatement1.setString(2, String.valueOf((getNagetiveMarksPerItemByPaperIdAndEventID(eventID,paperId)*-1)));
}
dmlPreparedStatement1.addBatch();
int[] count = dmlPreparedStatement.executeBatch();
count = dmlPreparedStatement1.executeBatch();
dbConnection.commit();
return true;