使用BatchPreparedStatementSetter 完成批量插入資料的操作
程式碼如下:
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("814120_"+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("批量插入資料完成!");
}
//結果如下:
}