# PostgreSQL 的 SQL 语句参数上限

描述:

PostgreSQL 的 SQL 语句参数上限 An I/O error occurred while sending to the backend

事故现场:

数据库我用 postgreSQL,持久层框架 mybatis

现在有一个操作,需要将一个大批数据 (3000+) 插入数据库,后台直接报错,报错原因如下:

org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
Caused by: java.io.IOException: Tried to send an out-of-range integer as a 2-byte value: 50805

原因:

批量插入的顶峰在 JDBC-Driver 出现天花板

简单来说就是 SQL 语句参数上限

解决思路:

我们可以将 (3000+) 大批数据集合分批来进行插入数据库

解决方式如下:

使用 Guava 库中的工具类 Lists.partition

// 定义存放大批量数据集合的集合
List<...> lists = new ArrayList<>();
for(...) {
    // 处理大批量数据并添加到 大批量数据的集合中
    lists.add(...);
}
// 将 lists 大批数据集合的数据 每 500 条数据分一组
List<List<...>> partition = Lists.partition(lists, 500);
for(List<...> item : partition) {
    // 每次批量插入 500 条
    mapper.insertBath(item);
}