将多条SQL添加到一个批中,一次性将批发送给数据库,数据库依次执行SQL语句,减小SQL语句发送的次数,提高程序运行的效率。java
优势:sql
缺点:数据库
没有预编译机制,不能防止sql注入攻击,且执行效率低。数组
SQL语句没法预留在数据库服务器中,每次都是新发送一条SQL语句到达数据库,须要从新解读SQL语句。服务器
//Statement实现批处理操做 public static void main(String[] args) { //try-with-resource try (Connection conn = JDBCUtils.getConnection(); Statement stat = conn.createStatement()) { //添加进批 stat.addBatch("create table t1(id int,name varchar(20))"); stat.addBatch("insert into t1 values(1,'a')"); stat.addBatch("insert into t1 values(2,'b')"); stat.addBatch("insert into t1 values(3,'c')"); //执行批 int[] counts = stat.executeBatch(); //long[] longs = stat.executeLargeBatch(); System.out.println(Arrays.toString(counts)); } catch (SQLException e) { e.printStackTrace(); } }
void addBatch( String sql );添加进批,其实就是一个List中。code
int[] executeBatch();执行批处理get
须要注意的是,excuteBatch()不支持Select语句,否则会以下错误:it
java.sql.BatchUpdateException: Can not issue SELECT via executeUpdate() or executeLargeUpdate().
Java8对批处理的方法进行了加强:long[] longs = stat.executeLargeBatch();
io
executeLargeBatch()
方法将返回一个long类型的数组,很好理解,由于配套的单个处理的executeLargeUpdate()
返回的是单个的long型。若是SQL语句的返回结果大于Integer.MAX_VALUE
的话能够用这个,固然,一样不支持select语句。编译
优势:
缺点:
//PreparedStatement实现批处理操做 public static void main(String[] args) { String sql = "insert into t1 values(?,?)"; try (Connection conn = JDBCUtils.getConnection(); PreparedStatement pstat = conn.prepareStatement(sql)) { for (int i = 0; i < 100; i++) { pstat.setInt(1, i); pstat.setString(2, i + ""); pstat.addBatch(); if (i % 10 == 0) { //满10条 执行批处理 pstat.executeBatch(); //每10条执行完,释放 pstat.clearBatch(); } } //保证全部都能执行一次 pstat.executeBatch(); } catch (SQLException e) { e.printStackTrace(); } }
void clearBatch();清空当前批中的statement。