oracle在进行大量数据批量插入时,若不进行分批次插入的话,则会报错
Cause: java.sql.SQLSyntaxErrorException: ORA-00913: 值过多
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: ORA-00913: 值过多
错误信息如上,正常情况而言,这个错误是因为 值个数 比 插入的列 个数多导致的
为了规避此问题,现进入分批插入操作,具体核心代码如下:
try {
int a = 2000;//每次提交2000条
int loop = (int) Math.ceil(accountList.size() / (double) a);
List<AccountInfo> tempList = new ArrayList<>(a);
int start, stop;
for (int i = 0; i < loop; i++) {
tempList.clear();
start = i * a;
stop = Math.min(i * a + a - 1, accountList.size() - 1);
System.out.println("range:" + start + " - " + stop);
for (int j = start; j <= stop; j++) {
tempList.add(accountList.get(j));
}
mapper.batchInsertAccountInfoUseSeq(tempList);
System.out.println("已经插入" + (stop + 1) + " 条");
}
session.commit();
session.clearCache();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
} finally {
if (session != null) {
session.close();
}
}
long end = System.currentTimeMillis();
System.out.println("插入数据库执行时间 = " + (end - start1)/1000+"秒");
mapper.xml 文件中的sql 语句如下:
<insert id="batchInsertAccountInfoUseSeq" parameterType="java.util.List">
<selectKey resultType="long" keyProperty="id" order="BEFORE">
SELECT ACCOUNT_SEQ.NEXTVAL FROM dual
</selectKey>
INSERT INTO ACCOUNT_INFO(ID, USERNAME,PASSWORD,GENDER, EMAIL,CREATE_DATE)
SELECT ACCOUNT_SEQ.NEXTVAL, m.* FROM(
<foreach collection="list" index="" item="accountInfo"
separator="union all">
select
#{accountInfo.userName},
#{accountInfo.password},
#{accountInfo.gender},
#{accountInfo.email},
sysdate
from dual
</foreach>
) m
</insert>
测试100万条数据批量插入的时间为: