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 ... 
随机推荐
- java park unpark
			https://blogs.oracle.com/dave/a-race-in-locksupport-park-arising-from-weak-memory-models https://blo ... 
- c与c++相互调用机制分析与实现
			c++通常被称为Better c,多数是因为c++程序可以很简单的调用c函数,语法上基本实现兼容.最常用的调用方式就是c++模块调用c实现的dll导出函数,很简单的用法,使用extern " ... 
- FFmpeg Basics学习笔记(1)ffmpeg基础
			1 FFmpeg的由来 FFmpeg缩写中,FF指的是Fast Forward,mpeg是 Moving Pictures Experts Group的缩写.官网:ffmpeg.org 编译好的可执行 ... 
- PowerDesigner小技巧
			1. 附加:工具栏不见了 调色板(Palette)快捷工具栏不见了PowerDesigner 快捷工具栏 palette 不见了,怎么重新打开,找回来呢 上网搜索了一下”powerdesigner 图 ... 
- 将String转换成InputStream
			String str = "";//add your string contentInputStream inputStream = new ... 
- java 多线程 25 :线程和线程组的异常处理
			线程中出现异常 从上面代码可以看出来处理线程的异常 设置异常的两种方式 1.全局异常,也是静态异常,是个静态方法 , 类.setDefaultUncaughtExceptionHandler() 2. ... 
- Android开发(七)——判断网络状态
			项目中难免会出现使用网络的情况,使用网络前得进行网络判断,看网上的网友一般有多种实现版本. 第一种: // 是否有网络连接 public static boolean isNetworkConnect ... 
- 基于jQuery滑动分步式进度导航条代码
			分享一款基于jQuery滑动分步式进度导航条代码.这是一款基于jquery实现的网站注册动态步骤导航条代码.效果图如下: 在线预览 源码下载 实现的代码. html代码: <div id=& ... 
- Python开源机器学习框架:Scikit-learn六大功能,安装和运行Scikit-learn
			Python开源机器学习框架:Scikit-learn入门指南. Scikit-learn的六大功能 Scikit-learn的基本功能主要被分为六大部分:分类,回归,聚类,数据降维,模型选择和数据预 ... 
- [转]Oracle中Hint深入理解
			原文地址:http://czmmiao.iteye.com/blog/1478465 Hint概述 基于代价的优化器是很聪明的,在绝大多数情况下它会选择正确的优化器,减轻了DBA的负担.但有时它也聪明 ... 
