【发布时间】:2020-07-20 15:29:58
【问题描述】:
我的代码遇到了一些事务的 SQL Server 死锁问题。所以,我实现了一个重试逻辑来克服同样的问题。现在,我面临一个新问题。问题是,每当它重试时,尝试执行的批处理在从异常中恢复后将被清空/清除。这导致缺少数据插入/更新。请帮我解决这个问题。
总结: 如果发生异常(SQLException | BatchUpdateException),则重试preparedstatement批处理
当前实施:
do {
try {
if (isInsert) {
int[] insertRows = psInsert.executeBatch();
psInsert.clearBatch();
System.out.println("insertRowsSuccess:" + Arrays.toString(insertRows));
} else {
int[] updateRows = psUpdate.executeBatch();
psUpdate.clearBatch();
System.out.println("updateRowsSuccess:" + Arrays.toString(updateRows));
}
break;
} catch (BatchUpdateException e) {
conn.rollback();
if (++count == maxTries) {
System.out.println(e.getMessage());
getFailedRecords(e, operation);
}
} catch (SQLException e) {
if (++count == maxTries) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
}
}
System.out.println("Tries:" + count);
} while (true);
private static void getFailedRecords(BatchUpdateException ex, String operation) {
int[] updateCount = ex.getUpdateCounts();
ArrayList<Integer> failedRecsList = new ArrayList<Integer>();
int failCount = 0;
for (int i = 0; i < updateCount.length; i++) {
if (updateCount[i] == Statement.EXECUTE_FAILED) {
failCount++;
failedRecsList.add(i);
}
}
System.out.println(operation + " Failed Count: " + failCount);
System.out.println(operation + " FailedRecordsIndex:" + failedRecsList);
}
【问题讨论】:
标签: java jdbc prepared-statement sqlexception