spring JdbcTemplate批量更新

 

spring JdbcTemplate 的批量更新:

1、JdbcTemplate batchUpdate(new String[]{});

一次执行多个sql语句;

2、

Java代码 复制代码  收藏代码
  1. final List tmpList = ....;   
  2. int count = JdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter(){   
  3.             public int getBatchSize() {   
  4.                 return tmpList.size();   
  5.             }   
  6.             public void setValues(PreparedStatement ps, int i)throws SQLException {   
  7.                 ps.setString(1, tmpList .get(i).getName());   
  8.                 ps.setString(2,tmpList .get(i).getCode());   
  9.                 ps.setString(3,tmpList .get(i).getDate());   
  10.                 ps.setInt(4,tmpList .get(i).getRank());   
  11.             }}).length;  
final List tmpList = ....;
int count = JdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter(){
			public int getBatchSize() {
				return tmpList.size();
			}
			public void setValues(PreparedStatement ps, int i)throws SQLException {
				ps.setString(1, tmpList .get(i).getName());
				ps.setString(2,tmpList .get(i).getCode());
				ps.setString(3,tmpList .get(i).getDate());
				ps.setInt(4,tmpList .get(i).getRank());
			}}).length;

 此方法可以批量,但是在spring里面是一条一条执行的,大批数据执行效率不佳

3、写PreparedStatement 进行批量

Java代码
  1. final List<TmpBean> tmpBeanList=...;   
  2. final String sql = ....;   
  3. int[] count = (int[]) this.pushJdbcTemplate.execute(sql, new PreparedStatementCallback(){   
  4.             public Object doInPreparedStatement(PreparedStatement ps)throws SQLException, DataAccessException {   
  5.                 int length = stockRanList.size();   
  6.                 ps.getConnection().setAutoCommit(false);   
  7.                 for(int i=0;i<length;i++){   
  8.                     ps.setString(1, tmpBeanList.get(i).getName());   
  9.                     ps.setString(2,tmpBeanList.get(i).getCode());   
  10.                     ps.setString(3,tmpBeanList.get(i).getDate());   
  11.                     ps.setInt(4,tmpBeanList.get(i).getRank());   
  12.                     ps.addBatch();   
  13.                 }   
  14.                 Object o = ps.executeBatch();   
  15.                 ps.getConnection().commit();   
  16.                 ps.getConnection().setAutoCommit(true);   
  17.                              //如果用<aop:config>  来控制事务,需要把上一行注掉,否则会报错   
  18.                 return  o;   
  19.             }});  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值