此范例有两个方法,create和createBatch。
批处理最主要的是效率提高,比一次次的处理数据所用的时间更短。
Java语言:
package cn.iego.wudi.jdbc;
import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class BatchTest { public static void main(String[] args) throws Exception { //处理100条数据 long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { create(i); } long end = System.currentTimeMillis(); System.out.println("creat:"+(end-start)); //100条数据批量处理 start = System.currentTimeMillis(); createBatch(); end = System.currentTimeMillis(); System.out.println("createBatch:"+(end-start)); } //批处理 private static void createBatch() { ResultSet rs = null; Connection conn = null; PreparedStatement ps =null; String sql = "insert into user(name,birthday,money) values (?,?,?)"; try { //jdbcUtils.getConnection()为自建工具类,用于获得数据库连接 conn = jdbcUtils.getConnection(); ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); //100条数据加入批处理 for (int j = 0; j < 100; j++) { ps.setString(1, "batch name " + j); ps.setDate(2, new Date(System.currentTimeMillis())); ps.setFloat(3, 2000 + j); ps.addBatch(); } //执行批处理 ps.executeBatch(); } catch (Exception e) { e.printStackTrace(); } } //普通处理 public static int create(int i) throws Exception{ ResultSet rs = null; Connection conn = null; PreparedStatement ps =null; String sql = "insert into user(name,birthday,money) values (?,?,?)"; try { conn = jdbcUtils.getConnection(); ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); ps.setString(1, "ps name "+i); ps.setDate(2, new Date(System.currentTimeMillis())); ps.setFloat(3, 2000+i); ps.executeUpdate(); rs = ps.getGeneratedKeys(); if (rs.next()) { return rs.getInt(1); } } catch (Exception e) { e.printStackTrace(); } return -1; } } |
|