我使用下面的代码来做同样的事情。每当发生sql错误(例如:数字超出范围)时,批处理更新就会停止,并将结果(int array)获取为null。所以我补充说 ignore
到 update
声明。
现在批处理正在完成,忽略sqlerror。这次我得到failureid(跳过的id)和successid(处理的id以及错误和异常)。但我要成功、失败、错误和异常的计数/ID分开。我该怎么做?
我还补充道 rewriteBatchedStatements=true
这有助于在插入时获得大量时间,但更新仍存在性能问题。更新3000条记录似乎需要10-20秒。我如何克服这个问题?
使用的技术:spring、springjdbctemplate、mysql、intellij idea、java。
List<String> successList = new ArrayList<>();
List<String> failureList = new ArrayList<>();
int result[] = null;
int count = 0;
int successCount = 0;
int failCount = 0;
int notAavailable = 0;
int resultSetIndx = 0;
try {
result = jdbcTemplate.batchUpdate(
"update ignore xxx set yy = ?, zz = ? where aa = ?",
new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps,int i) throws SQLException {
ps.setDouble(1, Double.parseDouble(new JSONObject(jsonArray.get(i).toString()).get("aa").toString()));
ps.setDouble(2, Double.parseDouble(new JSONObject(jsonArray.get(i).toString()).get("bb").toString()));
ps.setString(3, new JSONObject(jsonArray.get(i).toString()).get("cc").toString());
}
public int getBatchSize() {
return jsonArray.length();
}
} );
for(int affectedRow : result){
if(affectedRow == 0){
failureList.add(new JSONObject(jsonArray.get(failCount+successCount).toString()).get("u_item_code").toString());
failCount++;
}else{
successList.add(new JSONObject(jsonArray.get(failCount+successCount).toString()).get("u_item_code").toString());
successCount++;
}
resultSetIndx++;
}
System.out.println("failCount = "+failCount);
System.out.println("successcount = "+successCount);
System.out.println(failureList);
System.out.println(successList);
}
catch (DataAccessException e){
Throwable rootCause = e.getRootCause();
System.out.println("Batch update failed: "+e);
if(rootCause instanceof BatchUpdateException){
try{
System.out.println("inside instance of batchupdateexception");
BatchUpdateException bue = (BatchUpdateException)rootCause;
int lastSuccessfullRow = bue.getUpdateCounts().length;
int failurePoint = lastSuccessfullRow+1;
int continuePoint = lastSuccessfullRow+2;
successCount+=lastSuccessfullRow;
failCount++;
System.out.println("Last successful row: "+lastSuccessfullRow);
System.out.println("Failed row: "+failurePoint);
System.out.println("continue point: "+continuePoint);
}catch(Exception exp){
System.out.println("Error occured at batch update"+exp.getMessage());
throw new Exception(exp);
}
}else{
//if rootcause is not BatchUpdateException, then re-throw the exception
throw new Exception(e);
}
}catch(Exception exp){
System.out.println("Exception occured"+exp);
throw new Exception(exp);
}
暂无答案!
目前还没有任何答案,快来回答吧!