关于MyBatis批量插入SqlServer报:RPC 请求中提供了过多的参数。最多应为 2100。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hzw2312/article/details/80111000

java环境:Spring+SpringMVC+MyBatis

数据库:SqlServer 2008 R2

具体错误:

org.springframework.jdbc.UncategorizedSQLException: 
### Error updating database.  Cause: com.microsoft.sqlserver.jdbc.SQLServerException: 传入的表格格式数据流(TDS)远程过程调用(RPC)协议流不正确。此 RPC 请求中提供了过多的参数。最多应为 2100。

MyBatis代码:

<insert id="insertCompanyByArray" parameterType="java.util.List">
		insert into tb_company (company_name,company_area,address_detail) values 
		<foreach collection="list" item="a" index="index" separator =","> 
			(#{a.company_name},#{a.company_area},#{a.address_detail})
		</foreach>
	</insert>

SQL server对传入的参数大小有要求,怎么办?

解决办法,分批次提交,比如一次先提交500条,如果你插入的项实在太多,你在把值调低一些。

public int insertCompanyByArray(List<Map<String, Object>> list) {
		// TODO Auto-generated method stub
		int resultInt = 0;
		int batchCount = 500;// 每批commit的个数
        int batchLastIndex = batchCount;// 每批最后一个的下标
        for (int index = 0; index < list.size();) {
            if (batchLastIndex >= list.size()) {
                batchLastIndex = list.size();
                resultInt = resultInt * companyMapper.insertCompanyByArray(list.subList(index, batchLastIndex));
                System.out.println("index:" + index+ " batchLastIndex:" + batchLastIndex);
                break;// 数据插入完毕,退出循环
            } else {
            	resultInt = resultInt * companyMapper.insertCompanyByArray(list.subList(index, batchLastIndex));
                System.out.println("index:" + index+ " batchLastIndex:" + batchLastIndex);
                index = batchLastIndex;// 设置下一批下标
                batchLastIndex = index + (batchCount - 1);
            }
        }
		return resultInt;
	}

猜你喜欢

转载自blog.csdn.net/hzw2312/article/details/80111000