postgresql对sql语句参数数量的限制:Tried to send an out-of-range integer as a 2-byte value

postgresql对于sql语句的参数数量是有限制的,最大为32767。

postgresql源代码为:

public void sendInteger2(int val) throws IOException {
        if (val >= -32768 && val <= 32767) {
            this.int2Buf[0] = (byte)(val >>> 8);
            this.int2Buf[1] = (byte)val;
            this.pgOutput.write(this.int2Buf);
        } else {
            throw new IOException("Tried to send an out-of-range integer as a 2-byte value: " + val);
        }
    }

从源代码中可以看到pgsql使用2个字节的integer,故其取值范围为[-32768, 32767]。

这意味着sql语句的参数数量,即行数*列数之积必须小于等于32767.

如果一次插入的数据量太多,使得参数数量超过了最大值,只能分批插入了。

解决方法

将原有list进行分割:

假如表有10列,那么一次最多插入3276行。具体代码如下:

public void insertBatch(List list){
        int numberBatch = 32767; //每一次插入的最大行数
        double number = list.size() * 1.0 / numberBatch;
        int n = ((Double)Math.ceil(number)).intValue(); //向上取整
        for(int i = 0; i < n; i++){
            int end = numberBatch * (i + 1);
            if(end > list.size()){ 
                end = list.size(); //如果end不能超过最大索引值
            }
            insert(list.subList(numberBatch * i , end)); //插入数据库
        }
    }

参考文章:

1 https://www.cnblogs.com/miaoying/p/11227519.html

2 https://blog.csdn.net/haiyoung/article/details/83445990?ops_request_misc=%7B%22request%5Fid%22%3A%22158165410119726874012572%22%2C%22scm%22%3A%2220140713.130056874..%22%7D&request_id=158165410119726874012572&biz_id=0&utm_source=distribute.pc_search_result.none-task

3 https://blog.csdn.net/zljjava/article/details/47044163

4 https://stackoverflow.com/questions/49274390/postgresql-and-hibernate-java-io-ioexception-tried-to-send-an-out-of-range-inte

                  

你可能感兴趣的:(数据库)