【发布时间】:2020-05-24 07:53:57
【问题描述】:
我的业务场景是读取一个csv文件及其内容,然后持久化到oracle数据库中。
考虑其中包含 1000 行的 csv 文件。迭代每一行及其列的值并设置为preparedstatement,然后使用preparedStatement.addBatch()添加到批处理中,然后执行批处理。参考下面的例子。
try {
for(List<String> mainList:dataList) { //lines
int i=1;
ps = conn.prepareStatement(insertQuery);
for(String value:mainList) { //column values
ps.setString(i++, value);
}
ps.addBatch();
}
int[] updateCounts = ps.executeBatch(); //50th record not valid
} catch(BatchUpdateException e){
int[] updateCounts = e.getUpdateCounts();
}
这里 addbatch 将包含所有行 (1000) 和值,例如第 50 条记录值无效。截至目前,在数据库表中正确执行(插入)了 49 条记录。在第 50 条记录插入时,executebatch 在 catch 块中抛出 BatchUpdateException(这可能是任何问题),因为不是有效的记录。
此后,流程被阻塞,不再继续执行批处理中剩余的 950 条记录。我想要的是一旦抛出异常,我的代码应该运行并在数据库中插入剩余的 950 条记录。
请帮助解决此问题或提供任何其他替代方法来实现此逻辑。
CSV 示例:
Name,Id,Firstname,Lastname
Bharathi,2070,Bharathi,Raja --> row 1
Craig,Text,Craig,Johnson --> row 2
Mary,9346,Mary,Jenk --> row 3
考虑第 2 行是第 50 条记录,Id 是 Text 的值是无效的,它应该是数字,所以抛出异常。
我在 pom.xml 中有以下依赖项并使用 Spring Boot 应用程序
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.2</version>
</dependency>
【问题讨论】: