以下是使用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
SQL

编译上面代码,如下 -

F:\worksp\jdbc>javac -Djava.ext.dirs=F:\worksp\jdbc\libs BatchingWithStatement.java
Shell

执行上面代码如下所示 -

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>
Shell
 

JDBC Statement对象执行批量处理实例的更多相关文章

  1. JDBC PrepareStatement对象执行批量处理实例

    以下是使用PrepareStatement对象进行批处理的典型步骤顺序 - 使用占位符创建SQL语句. 使用prepareStatement()方法创建PrepareStatement对象. 使用se ...

  2. 使用Statement对象执行静态sql语句

    import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java ...

  3. statement 对象执行sql语句

    statement对象执行sql语句    关于Statement.它是Java执行数据库操作的一个重要步骤,可以执行一些简单的SQL语句,从而完成对数据库的操作.它有两个子接口,分别是Prepare ...

  4. jdbc中的Statement对象和Preparedstatement对象的区别,以及通过jdbc操作调用存储过程

    一. java.sql.*   和  javax.sql.*的包的类结构 |- Driver接口: 表示java驱动程序接口.所有的具体的数据库厂商要来实现此接口. |- connect(url, p ...

  5. JDBC的Statement对象

    以下内容引用自http://wiki.jikexueyuan.com/project/jdbc/statements.html: 一旦获得了数据库的连接,就可以和数据库进行交互.JDBC的Statem ...

  6. Statement对象

    Statement 对象 创建 Statement 对象 在你准备使用 Statement 对象执行 SQL 语句之前,你需要使用 Connection 对象的 createStatement() 方 ...

  7. java中Statement 对象

    1.创建Statement对象建立了到特定数据库的连接之后,就可用该连接发送 SQL 语句.Statement 对象用 Connection 的方法 createStatement 创建,如下列代码段 ...

  8. JDBC课程2--实现Statement(用于执行SQL语句)--使用自定义的JDBCTools的工具类静态方法,包括insert/update/delete三合一

    /**JDBC课程2--实现Statement(用于执行SQL语句) * 1.Statement :用于执行SQL语句的对象: * 1): 通过Connection 的createStatement( ...

  9. Spring JDBC Framework详解——批量JDBC操作、ORM映射

    转自:https://blog.csdn.net/yuyulover/article/details/5826948 一.spring JDBC 概述 Spring 提供了一个强有力的模板类JdbcT ...

随机推荐

  1. angular学习笔记(三十一)-$location(2)

    之前已经介绍了$location服务的基本用法:angular学习笔记(三十一)-$location(1). 这篇是上一篇的进阶,介绍$location的配置,兼容各版本浏览器,等. *注意,这里介绍 ...

  2. Kafka: Producer (0.10.0.0)

    转自:http://www.cnblogs.com/f1194361820/p/6048429.html 通过前面的架构简述,知道了Producer是用来产生消息记录,并将消息以异步的方式发送给指定的 ...

  3. 【Cmd】那些年,我们迷恋的cmd命令(二)

    那些年,我们迷恋的命令(一) 那些年,我们迷恋的命令(二) Linux系统下基本命令 Linux系统下基本命令: 要区分大小写 uname 显示版本信息(同win2K的 ver) dir 显示当前目录 ...

  4. webpack打包调试react并使用babel编译jsx配置方法

    http://lxj8749.iteye.com/blog/2287074 ********************************************** 安装webpack npm i ...

  5. tf.nn.sigmoid_cross_entropy_with_logits

    tf.nn.sigmoid_cross_entropy_with_logits sigmoid_cross_entropy_with_logits( _sentinel=None, labels=No ...

  6. eclipse Maven项目Context root 为空,不能修改

    从SVN下载项目的时候,遇到过这种问题,导入下来的项目没有Context root 的名字,导致报错. 看了网上的解决办法,不行,于是研究了下,得出了解决办法,这里来记录一下. 先将Maven项目下载 ...

  7. JAVA传入一个字符串,返回一个字符串中的大写字母

    /**      *       * @param 传入一个字符串      * @return 返回一个字符串中的大写字母      */     private static String str ...

  8. hive INSERT OVERWRITE table could not be cleaned up.

    create table maats.account_channel ROW FORMAT DELIMITED FIELDS TERMINATED BY '^' STORED AS TEXTFILE ...

  9. WPF System.InvalidCastException: 无法将类型为“System.Windows.Media.Color”的对象强制转换为类型“System.Windows.Media.Brush”。

    场景:添加ComboBox样式,界面卡死,日志异常文件如下: -- ::, | ERROR | System.InvalidCastException: 无法将类型为“System.Windows.M ...

  10. python抓取今日头条

    # 直接上代码,抓取关键词搜索结果的json数据# coding:utf-8 import requests import json url = 'http://www.toutiao.com/sea ...