JDBC-Driver、PostgreSQL的SQL语句参数上限错误分析及解决办法(源码)

JDBC-Driver、PostgreSQL的SQL语句参数上限错误分析及解决办法(源码)

Mybatis + PostgreSQL-JDBC-Driver 42.1.4批量插入24178条数据(每条30字段).报如下错误:

pSQL 9.6

Cause: org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
; SQL []; An I/O error occurred while sending to the backend.; nested exception is org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
Tried to send an out-of-range integer as a 2-byte value: 647430

没想到批量插入的顶峰在JDBC-Driver这里首先出现天花板.

原因:

  • 这里是JDBC-Driver 一条SQL**参数数量达到了上限,幂增操作的参数=记录数(行)插入的字段数(列)*.
  • JDBC-Driver 支持的参数数量跟版本(x.y.z)和类型(xx数据库)有关.

解决思路:

分割成小段提交.

解决办法:

@Service
public class ChPeriodicalThesisService {

    @Autowired
    private ChPeriodicalThesisMapper thesisDao;

    //其他CRUD...

    /**
     * .
     * TODO  批量插入
     * @param thesisList
     * @return
     * @throws Exception
     */
    public int insertList(List thesisList) throws Exception {
        return thesisDao.insertList(thesisList);
    }

    /**
     * .
     * TODO 递归:分割长List为 subNum/段。
     * @param thesisList 论文list(总)
     * @param subNum 每段长度 (最小1)
     * @return
     * @throws Exception
     */
    private int recurSub(List thesisList,int subNum) throws Exception{
        //参数合法性判断:
        if(thesisList.isEmpty()) return 0;
        if(subNum<1) return 0;

        //大于subNum,进入分割
        if(thesisList.size() > subNum) {// && !(thesisList.isEmpty())
            //将前subNum分出来,直接插入到数据库。
            List toInsert = thesisList.subList(0, subNum);
            //将subNum至最后 (剩余部分) 继续进行递归分割
            List toRecurSub = thesisList.subList(subNum, thesisList.size());

            //将前subNum分出来,直接插入到数据库 && 将subNum至最后 (剩余部分) 继续进行递归分割 。统计数量
            return insertList(toInsert) + recurSub(toRecurSub,subNum);

        //少于subNum,直接插入数据库 (递归出口)
        }else {
            //插入到数据库。统计数量
            return insertList(thesisList);
        }
    }


    /**
     * .
     * TODO 将数据流读取并批量插入
     * @param in
     * @return
     * @throws Exception
     */
    public int readStreamAndInsertList(InputStream in) throws Exception {
        FileUtil fileUtil = new FileUtil();
        List thesisList = fileUtil.importFileOfChPeriodicalThesis(in);

        //每1500为一段 插入
        return recurSub(thesisList,1500);
    }
}

源码: 欢迎交流.

https://github.com/timo1160139211/trans

参考资料:

https://stackoverflow.com/questions/20878854/postgresql-exception-org-postgresql-util-psqlexception-an-i-o-error-occured-w

效果:
JDBC-Driver、PostgreSQL的SQL语句参数上限错误分析及解决办法(源码)_第1张图片

JDBC-Driver、PostgreSQL的SQL语句参数上限错误分析及解决办法(源码)_第2张图片

你可能感兴趣的:(PostgreSQL,JDBC)