JDBC Statement对象执行批量处理实例
以下是使用Statement对象的批处理的典型步骤序列 -
- 使用
createStatement()方法创建Statement对象。 - 使用
setAutoCommit()将自动提交设置为false。 - 使用
addBatch()方法在创建的Statement对象上添加SQL语句到批处理中。 - 在创建的
Statement对象上使用executeBatch()方法执行所有SQL语句。 - 最后,使用
commit()方法提交所有更改。
此示例代码是基于前面章节中完成的环境和数据库设置编写的。
以下代码片段提供了使用Statement对象的批量更新示例,将下面代码保存到文件:BatchingWithStatement.java -
// Import required packages
// See more detail at http://www.yiibai.com/jdbc/
import java.sql.*;
public class BatchingWithStatement {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "root";
static final String PASS = "123456";
public static void main(String[] args) {
Connection conn = null;
Statement 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 statement
System.out.println("Creating statement...");
stmt = conn.createStatement();
// Set auto-commit to false
conn.setAutoCommit(false);
// First, let us select all the records and display them.
printRows( stmt );
// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(200,'Curry', 'Stephen', 30)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);
// Create one more SQL statement
SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(201,'Kobe', 'Bryant', 35)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);
// Create one more SQL statement
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();
// 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
编译上面代码,如下 -
F:\worksp\jdbc>javac -Djava.ext.dirs=F:\worksp\jdbc\libs BatchingWithStatement.java
执行上面代码如下所示 -
F:\worksp\jdbc>java -Djava.ext.dirs=F:\worksp\jdbc\libs BatchingWithStatement
Connecting to database...
Thu Jun 01 04:41:05 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Creating statement...
Displaying available rows...
ID: 100, Age: 28, First: Max, Last: Su
ID: 101, Age: 25, First: Wei, Last: Wang
ID: 102, Age: 35, First: Xueyou, Last: Zhang
ID: 103, Age: 30, First: Jack, Last: Ma
ID: 106, Age: 28, First: Curry, Last: Stephen
ID: 107, Age: 32, First: Kobe, Last: Bryant
Displaying available rows...
ID: 100, Age: 35, First: Max, Last: Su
ID: 101, Age: 25, First: Wei, Last: Wang
ID: 102, Age: 35, First: Xueyou, Last: Zhang
ID: 103, Age: 30, First: Jack, Last: Ma
ID: 106, Age: 28, First: Curry, Last: Stephen
ID: 107, Age: 32, First: Kobe, Last: Bryant
ID: 200, Age: 30, First: Curry, Last: Stephen
ID: 201, Age: 35, First: Kobe, Last: Bryant
Goodbye!
F:\worksp\jdbc>
JDBC Statement对象执行批量处理实例的更多相关文章
- JDBC PrepareStatement对象执行批量处理实例
以下是使用PrepareStatement对象进行批处理的典型步骤顺序 - 使用占位符创建SQL语句. 使用prepareStatement()方法创建PrepareStatement对象. 使用se ...
- 使用Statement对象执行静态sql语句
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java ...
- statement 对象执行sql语句
statement对象执行sql语句 关于Statement.它是Java执行数据库操作的一个重要步骤,可以执行一些简单的SQL语句,从而完成对数据库的操作.它有两个子接口,分别是Prepare ...
- jdbc中的Statement对象和Preparedstatement对象的区别,以及通过jdbc操作调用存储过程
一. java.sql.* 和 javax.sql.*的包的类结构 |- Driver接口: 表示java驱动程序接口.所有的具体的数据库厂商要来实现此接口. |- connect(url, p ...
- JDBC的Statement对象
以下内容引用自http://wiki.jikexueyuan.com/project/jdbc/statements.html: 一旦获得了数据库的连接,就可以和数据库进行交互.JDBC的Statem ...
- Statement对象
Statement 对象 创建 Statement 对象 在你准备使用 Statement 对象执行 SQL 语句之前,你需要使用 Connection 对象的 createStatement() 方 ...
- java中Statement 对象
1.创建Statement对象建立了到特定数据库的连接之后,就可用该连接发送 SQL 语句.Statement 对象用 Connection 的方法 createStatement 创建,如下列代码段 ...
- JDBC课程2--实现Statement(用于执行SQL语句)--使用自定义的JDBCTools的工具类静态方法,包括insert/update/delete三合一
/**JDBC课程2--实现Statement(用于执行SQL语句) * 1.Statement :用于执行SQL语句的对象: * 1): 通过Connection 的createStatement( ...
- Spring JDBC Framework详解——批量JDBC操作、ORM映射
转自:https://blog.csdn.net/yuyulover/article/details/5826948 一.spring JDBC 概述 Spring 提供了一个强有力的模板类JdbcT ...
随机推荐
- Flink papers
Around 2009 the Stratosphere research project started at the TU Berlin which a few years later was s ...
- (原创)c++11改进我们的模式之改进表驱动模式
所谓表驱动法(Table-Driven Approach),简单讲是指用查表的方法获取值.表驱动是将一些通过较为复杂逻辑语句来得到数据信息的方式,通过查询表的方式来实现,将数据信息存放在表里.对于消除 ...
- MyBean 框架入门手册<感谢[青铜]整理的如此细致和系统>
MyBean 框架入门手册 2014/9/15 by lighttop 目 录 MyBean 框架学习笔记............................................... ...
- 玩转Bootstrap(JS插件篇)-第1章 模态弹出框 :1-2 动画过渡
动画过渡(Transitions) 这一小节我们先来讲“动画过渡(Transitions)”这个插件的使用,源文件:transition.js Bootstrap框架默认给各个组件提供了基本动画的过渡 ...
- LeetCode: 【L4】N-Queens 解题报告
[L4]N-Queens 解题报告 N-Queens Total Accepted: 16418 Total Submissions: 63309 My Submissions The n-queen ...
- 【Ubuntu】ubuntu系统下python3和python2环境自由切换
shell里执行: sudo update-alternatives --install /usr/bin/python python /usr/local/lib/python2.7 100sudo ...
- 如何在CentOS或者RHEL上启用Nux Dextop仓库 安装shutter截图工具
Nux Dextop是一个面对CentOS.RHEL.ScientificLinux的含有许多流行的桌面和多媒体相关的包的第三方RPM仓库(比如:Ardour,Shutter等等).目前,Nux De ...
- Python MQTT 最简单例程搭建
MQTT 不是普通的 client server 模型,他还加了一个 代理者. 根据剑锋的提示,先下载了 paho-mqtt 模块, ubuntu 14.04 上下载方法如下: sudo apt-ge ...
- IoCopyCurrentIrpStackLocationToNext与IoSetCompletionRoutine的深入理解
1.IoCopyCurrentIrpStackLocationToNext是拷贝本层的IO_STACK_LOCATION 到下一层.在楚狂人的驱动教程中说:如果对irp完成之后的事情有兴趣,并打算在完 ...
- 分布式session实现
1.为什么要做分布式session 前段时间在做hibernate和docker集成时,在web项目落地时遭遇session粘性的困扰,同一个用户的申请落到不同服务端时,会发生session丢失的问题 ...