以下内容引用自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. 跨库导表数据(sql)

    程序员用 列子: insert into "000".tbFreeReportselect ReportCode ,ReportName ,GroupNamefrom openda ...

  2. iOS---iPad开发及iPad特有的特技

    iPad开发简单介绍 iPad开发最大的不同在于iPhone的就是屏幕控件的适配,以及横竖屏的旋转. Storyboard中得SizeClass的横竖屏配置,也不支持iPad开发. 1.在控制器中得到 ...

  3. sql语句中截取字符串

    今天在开发过程中因为要用到合并单元格,在程序里实现了以后,查出来的数据太长,都把格式撑大了,后来想想可以在sql语句查询的时候就截取,就去网上找了一下,挺好用,就转了过来: 合并单元格: /// &l ...

  4. webpack3.0版本的一些改动

    npm install --save / npm install -S 项目发布上线之后还会依赖用到的插件,没有这些插件,项目不能运行 npm install --save-dev / npm ins ...

  5. Int 1的实现过程 (一)

    闲话少说,直奔主题,首先OD载入一个程序,然后执行一下单步(调试器会将TF置1) 此时,CPU会在基于当前线程上下文的环境中,进入int 1的中断门,也就是KiTrap01 kd> !idt - ...

  6. iisexpress局域网内调试网站

    1.找到IISExpress目录 IISExpress\config\applicationhost.config(注:如果使用vs2015则更改解决方案目录下的.vs文件夹中的该文件) <si ...

  7. oracle数据库使用hint来让模糊查询走索引

    在没有创建数据直方图之前,查询优化器是cbo,可能不会选择代价最低(效率最高)的方式查询. 先创建表 --日语假名表 CREATE TABLE JAPANESE_SOUNDMARK ( ID INTE ...

  8. jq进度条

    <!doctype html><html><head><meta charset="utf-8"><title>JQue ...

  9. 在git提交时忽略已提交过或从线上拉取下来但本地已修改的文件

    一.忽略: git update-index --assume-unchanged [file-path] 命令中的file-path 就是需要忽略提价的文件的路径 例子: git update-in ...

  10. js中给正则传参、传递变量

    js中验证字符串有时需要用到正则表达式,一般情况下直接写正则进行验证就行. 但是遇到需要把部分正则作为参数传递就麻烦一点,需要用到RegExp()对象. <script type="t ...