One - One Code All

Blog Content

使用BatchPreparedStatementSetter 完成批量插入数据的操作

Java   2010-06-19 22:38:15

JDBC使用MySQL处理大数据的时候,自然而然的想到要使用批处理,
普通的执行过程是:每处理一条数据,就访问一次数据库;
而批处理是:累积到一定数量,再一次性提交到数据库,减少了与数据库的交互次数,所以效率会大大提高
至于事务:事务指逻辑上的一组操作,组成这组操作的各个单元,要不全部成功,要不全部不成功,默认是关闭事务的。

既用事务,也用批处理,速度最快;

package com.jdbcTemplate1;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;

public class JdbcTemplateForBatchUpdate {

 //需要填充的数据量
 public static int  count=1000;
 /**
  * @param args
  */
 public static void main(String[] args) {
  ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
  
  DataSource dt=(DataSource) context.getBean("dataSource");
  //使用数据源转
  JdbcTemplate template=new JdbcTemplate(dt) ;
  
  //定义批量数据的列表
  final List stcdlist=new ArrayList();
  final List namelist=new ArrayList();
  
  //填充数据到列表 ;
  for (int i = 0; i < count; i++) {
   stcdlist.add("beijing_"+i);
   namelist.add("北京_"+i);
   
  }
  
  String sql="insert into pptn values(?,?)";
  //通过内部类创建批处理对象
  BatchPreparedStatementSetter bts=new BatchPreparedStatementSetter() {
   
   @Override
   public void setValues(PreparedStatement ps, int index) throws SQLException {
    ps.setString(1, (String) stcdlist.get(index));
    ps.setString(2, (String) namelist.get(index));
    
   }
   
   @Override
   public int getBatchSize() {
    // TODO Auto-generated method stub
    return count;
   }
  };
  //执行批插入数据
  template.batchUpdate(sql, bts);
  
  System.out.println("批量插入数据完成!");

 }



上一篇:java将总秒数转换为时分秒
下一篇:Spring.properties文件中将元素作为数组获取

The minute you think of giving up, think of the reason why you held on so long.