JDBC中的批处理
以下内容引用自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中的批处理的更多相关文章
- JDBC 中的事务和批处理 batch
JDBC事务处理: 事务处理一般在事务开始前把事务提交设置为false 所有DML语句执行完成后提交事务 demo: package com.xzlf.jdbc; import java.sql.Co ...
- jdbc基础 (四) 批处理
批处理,就是字面上的意思,一次性处理一批sql语句. 直接看例子吧: package com.cream.ice.jdbc; import java.sql.Connection; import ja ...
- 一、DAO设计模式 二、DAO设计模式的优化 三、JDBC中的事务,连接池的使用
一.DAO设计模式概述###<1>概念 DAO,Data Access Object ,用于访问数据库的对象. 位于业务逻辑和数据持久化层之间,实现对数据持久化层的访问 ...
- JDBC中的Statement和PreparedStatement的区别
JDBC中的Statement和PreparedStatement的区别
- [转]JDBC中日期时间的处理技巧
Java中用类java.util.Date对日期/时间做了封装,此类提供了对年.月.日.时.分.秒.毫秒以及时区的控制方法,同时也提供一些工具方法,比如日期/时间的比较,前后判断等. java.uti ...
- JDBC中的事务-Transaction
事务-Transaction 某些情况下我们希望对数据库的某一操作要么整体成功,要么整体失败,经典的例子就是支付宝提现.例如我们发起了支付宝到银行卡的100元提现申请,我们希望的结果是支付宝余额减少1 ...
- Oracle数据库编程:在JDBC中应用Oracle
9.在JDBC中应用Oracle: JDBC访问数据库基本步骤: 1.加载驱动 2.获取链接对象 3.创建SQL语句 4.提交S ...
- JDBC中的ResultSet无法多次循环的问题。
前几天碰见了一个很奇葩的问题,使我百思不得其解,今天就写一下我遇见的问题吧,也供大家参考,别和我犯同样的毛病. 首先说下jdbc,jdbc是java是一种用于执行SQL语句的Java API,从jdb ...
- 在JDBC中使用Java8的日期LocalDate、LocalDateTime
在实体Entity里面,可以使用java.sql.Date.java.sql.Timestamp.java.util.Date来映射到数据库的date.timestamp.datetime等字段 但是 ...
随机推荐
- struts2 <allowed-methods > 标签配置
1.在struts2 2.5版本中添加了对方法访问的权限,如果没有被添加到<allow-method> 方法的标签,将会报一下错误 5:05:18.078 [http-apr-8020 ...
- Farseer.net轻量级ORM开源框架 V1.2版本升级消息
V1.1到V1.2的更新,重构了很多类及方法,其中主要做了性能优化(取消所有反射,使用表达式树+缓存).解耦了SQL生成层(没有实体.队列的依赖,所有数据均通过表达式树传递解析) 先上内部更新历史记录 ...
- leetcode_712. Minimum ASCII Delete Sum for Two Strings
https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/ 给定两个string s1,s2,从s1和s2中删除一些 ...
- chown - 修改文件所有者和组别
总览 chown [options] user [:group] file... POSIX 选项: [-R] GNU 选项(最短格式): [-cfhvR] [--dereference] [--re ...
- JavaSE-24 多线程
学习要点 线程概述 Java中的多线程 线程状态 线程调度 线程同步 线程间通信 线程概述 1 进程 进程就是应用程序的执行实例. 进程特征: 动态性:动态产生,动态消亡.进程启动,系统为其分配资源 ...
- java was started but returned exit code =-805306369的处理方法
Myeclipse出现java was started but returned exit code =-805306369的错误,如图: 解决方法: 换个workspaces:换个工作目录,估计估计 ...
- JAVA基础——内存流
掌握内存操作流 输入和输出都是从文件中来的,当然,也可将输出的位置设置在内存上,这就需要ByteArrayInputStream和ByteArrayOutputStream ByteArrayInpu ...
- 路径工具类NSPathUtilities
路径工具类NSPathUtilities.h 路径类NSPathUtilities.h包含了 NSString的函数和分类扩展,他允许你操作路径名.应该竟可能的使用这些函数,以便使程序更独立于文件系统 ...
- 记一次被面试的final问题
---- 前言 今天面试被问到了,我们都知道final修饰的东西是不可变的,那么是值不可变还是其地址不可变?一脸懵逼,回来查阅一番,总结一下 --- final与数据 在日常行为下,一般数据指的都是基 ...
- 实现基于pam认证的vsftpd
1 需求 使用指定虚拟用户Allen与Barry登录ftp,认证的源是mysql服务器: Allen可以上传文件,Barry不可以上传文件: 2 环境 [root@centos7 ~]# cat /e ...