以下内容引用自http://wiki.jikexueyuan.com/project/jdbc/batch-processing.html

批处理是指将关联的SQL语句组合成一个批处理,并将他们当成一个调用提交给数据库。

当一次发送多个SQL语句到数据库时,可以减少通信的资源消耗,从而提高了性能。

  • JDBC驱动程序不一定支持该功能。可以使用DatabaseMetaData.supportsBatchUpdates()方法来确定目标数据库是否支持批处理更新。如果JDBC驱动程序支持此功能,则该方法返回值为true。

  • Statement,PreparedStatement和CallableStatement的addBatch()方法用于添加单个语句到批处理。

  • executeBatch()方法用于启动执行所有组合在一起的语句。

  • executeBatch()方法返回一个整数数组,数组中的每个元素代表了各自的更新语句的更新数目。

  • 正如可以添加语句到批处理中,也可以用clearBatch()方法删除它们。此方法删除所有用addBatch()方法添加的语句。但是,不能有选择性地选择要删除的语句。

一、批处理和Statement对象

使用Statement对象来使用批处理所需要的典型步骤如下所示:

  • 使用createStatement()方法创建一个Statement对象。
  • 使用setAutoCommit()方法将自动提交设为false。
  • 被创建的Statement对象可以使用addBatch()方法来添加想要的所有SQL语句。
  • 被创建的Statement对象可以用executeBatch()将所有的SQL语句执行。
  • 最后,使用commit()方法提交所有的更改。

示例:

下面的代码段提供了一个使用Statement对象批量更新的例子:

// Create statement object
Statement stmt = conn.createStatement(); // Set auto-commit to false
conn.setAutoCommit(false); // Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(200,'Zia', 'Ali', 30)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL); // Create one more SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(201,'Raj', 'Kumar', 35)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL); // Create one more SQL statement
String SQL = "UPDATE Employees SET age = 35 " + "WHERE id = 100";
// Add above SQL statement in the batch.
stmt.addBatch(SQL); // Create an int[] to hold returned values
int[] count = stmt.executeBatch(); //Explicitly commit statements to apply changes
conn.commit();

二、批处理和PrepareStatement对象

使用PrepareStatement对象来使用批处理需要的典型步骤如下所示:

  • 使用占位符创建SQL语句。
  • 使用任一prepareStatement()方法创建PrepareStatement对象。
  • 使用setAutoCommit()方法将自动提交设为false。
  • 被创建的Statement对象可以使用addBatch()方法来添加想要的所有SQL语句。
  • 被创建的Statement对象可以用executeBatch()将所有的SQL语句执行。
  • 最后,使用commit()方法提交所有的更改。

下面的代码段提供了一个使用PrepareStatement对象批量更新的示例:

// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(?, ?, ?, ?)"; // Create PrepareStatement object
PreparedStatemen pstmt = conn.prepareStatement(SQL); //Set auto-commit to false
conn.setAutoCommit(false); // Set the variables
pstmt.setInt( 1, 400 );
pstmt.setString( 2, "Pappu" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 33 );
// Add it to the batch
pstmt.addBatch(); // Set the variables
pstmt.setInt( 1, 401 );
pstmt.setString( 2, "Pawan" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 31 );
// Add it to the batch
pstmt.addBatch(); //add more batches
.
.
.
.
//Create an int[] to hold returned values
int[] count = stmt.executeBatch(); //Explicitly commit statements to apply changes
conn.commit();

示例:

//Import required packages
import java.sql.*; public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Test?serverTimezone=UTC"; // Database credentials
static final String USER = "root";
static final String PASS = "root"; public static void main(String[] args) {
Connection conn = null;
PreparedStatement stmt = null;
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver"); // Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS); // Create SQL statement
String SQL = "INSERT INTO Employees(id,first,last,age) " + "VALUES(?, ?, ?, ?)"; // Create preparedStatemen
System.out.println("Creating statement...");
stmt = conn.prepareStatement(SQL); // Set auto-commit to false
conn.setAutoCommit(false); // First, let us select all the records and display them.
printRows(stmt); // Set the variables
stmt.setInt(1, 400);
stmt.setString(2, "Pappu");
stmt.setString(3, "Singh");
stmt.setInt(4, 33);
// Add it to the batch
stmt.addBatch(); // Set the variables
stmt.setInt(1, 401);
stmt.setString(2, "Pawan");
stmt.setString(3, "Singh");
stmt.setInt(4, 31);
// Add it to the batch
stmt.addBatch(); // Create an int[] to hold returned values
int[] count = stmt.executeBatch(); // Explicitly commit statements to apply changes
conn.commit(); // Again, let us select all the records and display them.
printRows(stmt); // Clean-up environment
stmt.close();
conn.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
} // end try
System.out.println("Goodbye!");
}// end main public static void printRows(Statement stmt) throws SQLException {
System.out.println("Displaying available rows...");
// Let us select all the records and display them.
String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql); while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last"); // Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
System.out.println();
rs.close();
}// end printRows()
}// end JDBCExample

这将产生如下所示结果:

测试工程:https://github.com/easonjim/5_java_example/tree/master/jdbcbasics/test7

JDBC中的批处理的更多相关文章

  1. JDBC 中的事务和批处理 batch

    JDBC事务处理: 事务处理一般在事务开始前把事务提交设置为false 所有DML语句执行完成后提交事务 demo: package com.xzlf.jdbc; import java.sql.Co ...

  2. jdbc基础 (四) 批处理

    批处理,就是字面上的意思,一次性处理一批sql语句. 直接看例子吧: package com.cream.ice.jdbc; import java.sql.Connection; import ja ...

  3. 一、DAO设计模式 二、DAO设计模式的优化 三、JDBC中的事务,连接池的使用

    一.DAO设计模式概述###<1>概念 DAO,Data Access Object ,用于访问数据库的对象. 位于业务逻辑和数据持久化层之间,实现对数据持久化层的访问![](1.png) ...

  4. JDBC中的Statement和PreparedStatement的区别

    JDBC中的Statement和PreparedStatement的区别  

  5. [转]JDBC中日期时间的处理技巧

    Java中用类java.util.Date对日期/时间做了封装,此类提供了对年.月.日.时.分.秒.毫秒以及时区的控制方法,同时也提供一些工具方法,比如日期/时间的比较,前后判断等. java.uti ...

  6. JDBC中的事务-Transaction

    事务-Transaction 某些情况下我们希望对数据库的某一操作要么整体成功,要么整体失败,经典的例子就是支付宝提现.例如我们发起了支付宝到银行卡的100元提现申请,我们希望的结果是支付宝余额减少1 ...

  7. Oracle数据库编程:在JDBC中应用Oracle

    9.在JDBC中应用Oracle: JDBC访问数据库基本步骤:          1.加载驱动          2.获取链接对象          3.创建SQL语句          4.提交S ...

  8. JDBC中的ResultSet无法多次循环的问题。

    前几天碰见了一个很奇葩的问题,使我百思不得其解,今天就写一下我遇见的问题吧,也供大家参考,别和我犯同样的毛病. 首先说下jdbc,jdbc是java是一种用于执行SQL语句的Java API,从jdb ...

  9. 在JDBC中使用Java8的日期LocalDate、LocalDateTime

    在实体Entity里面,可以使用java.sql.Date.java.sql.Timestamp.java.util.Date来映射到数据库的date.timestamp.datetime等字段 但是 ...

随机推荐

  1. Java编程思想总结笔记Chapter 5

    初始化和清理是涉及安全的两个问题.本章简单的介绍“垃圾回收器”及初始化知识. 第五章  初始化与清理 目录:5.1 用构造器确保初始化5.2 方法重载5.3 默认构造器5.4 this关键字5.5 清 ...

  2. iOS---iOS中SQLite的使用

    一.SQLite的使用 采用SQLite数据库来存储数据.SQLite作为一中小型数据库,应用ios中,跟前三种保存方式相比,相对比较复杂一些.还是一步步来吧! 第一步:导入头文件 需要添加SQLit ...

  3. 详解java中staitc关键字

    一.static定义 static是静态修饰符意思,什么叫静态修饰符呢?大家都知道,在程序中任何变量或者代码都是在编译时由系统自动分配内存来存储的,而所谓静态就是指在编译后所分配的内存会一直存在,直到 ...

  4. Maven常用仓库地址以及手动添加jar包到仓库

    http://www.blogjava.net/fancydeepin 共有的仓库 http://repository.sonatype.org/content/groups/public/http: ...

  5. 04Hibernate连接数据库环境配置

    Hibernate连接数据库环境配置

  6. 散列的键值对没初始化时不要用print打印此值,不要用 . 操作符去连接打印 这个值。

    31 delete $vertical_alignment{$anonymous};     32 print $vertical_alignment{$anonymous}."\n&quo ...

  7. 全国高校绿色计算大赛 预赛第一阶段(Python)

    第1关将字符串反转 #!/usr/bin/env python # -*- coding: utf-8 -*- class Task: def inversion(self, str): # **** ...

  8. [Luogu] P1131 [ZJOI2007]时态同步

    题目描述 题目描述 小Q在电子工艺实习课上学习焊接电路板.一块电路板由若干个元件组成,我们不妨称之为节点,并将其用数字1,2,3…进行标号.电路板的各个节点由若干不相交的导线相连接,且对于电路板的任何 ...

  9. CURL PHP模拟浏览器get和post

    模拟浏览器get和post数据需要经常用到的类, 在这里收藏了几个不错的方法 方法一 <?php define ( 'IS_PROXY', true ); //是否启用代理 /* cookie文 ...

  10. Reparameterization Trick

    目录 Sample() is not differentiable Reparameterization trick Too Complex Sample() is not differentiabl ...