以下是使用PrepareStatement对象进行批处理的典型步骤顺序 -

  • 使用占位符创建SQL语句。
  • 使用prepareStatement()方法创建PrepareStatement对象。
  • 使用setAutoCommit()将自动提交设置为false
  • 使用addBatch()方法在创建的Statement对象上添加SQL语句到批处理中。
  • 在创建的Statement对象上使用executeBatch()方法执行所有SQL语句。
  • 最后,使用commit()方法提交所有更改。

此示例代码是基于前面章节中完成的环境和数据库设置编写的。

以下代码片段提供了使用PrepareStatement对象的批量更新示例,将下面代码保存到文件:BatchingWithPrepareStatement.java -

// Import required packages
// See more detail at http://www.yiibai.com/jdbc/ import java.sql.*; public class BatchingWithPrepareStatement {
// 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;
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, "Python" );
stmt.setString( 3, "Zhang" );
stmt.setInt( 4, 33 );
// Add it to the batch
stmt.addBatch(); // Set the variables
stmt.setInt( 1, 401 );
stmt.setString( 2, "C++" );
stmt.setString( 3, "Huang" );
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
SQL

编译上面代码,如下 -

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

执行上面代码如下所示 -

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

F:\worksp\jdbc>java -Djava.ext.dirs=F:\worksp\jdbc\libs BatchingWithPrepareStatement
Connecting to database...
Thu Jun 01 04:46:38 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: 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 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
ID: 400, Age: 33, First: Python, Last: Zhang
ID: 401, Age: 31, First: C++, Last: Huang Goodbye! F:\worksp\jdbc>

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

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

    以下是使用Statement对象的批处理的典型步骤序列 - 使用createStatement()方法创建Statement对象. 使用setAutoCommit()将自动提交设置为false. 使用 ...

  2. PrepareStatement对象进行批处理的典型步骤顺序

    https://www.yiibai.com/jdbc/preparestatement-batching-example.html 以下是使用PrepareStatement对象进行批处理的典型步骤 ...

  3. Java中反射机制和Class.forName、实例对象.class(属性)、实例对象getClass()的区别

    一.Java的反射机制   每个Java程序执行前都必须经过编译.加载.连接.和初始化这几个阶段,后三个阶段如下图:   其中

  4. 用JDBC编程的执行时错误及其解决大全

    用JDBC编程的执行时错误及其解决 用JDBC编程的执行时错误及其解决 源码: .java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlser ...

  5. 使用JDBC,完成数据库批量添加数据操作:

    第一步:定义一个key String key = "into 表名(字段1,字段2,字段3)"; 第二步:定义一个可以增长的变量 StringBuffer values = new ...

  6. mybatis执行批量更新update

    Mybatis的批量插入这里有http://ljhzzyx.blog.163.com/blog/static/38380312201353536375/.目前想批量更新,如果update的值是相同的话 ...

  7. 转:Filter的执行顺序与实例

    转:http://www.cnblogs.com/Fskjb/archive/2010/03/27/1698448.html Filter的执行顺序与实例 Filter介绍 Filter可认为是Ser ...

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

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

  9. 如何 ︰ 执行批量更新和插入使用.NET 提供程序在 C#.NET OpenXML

    https://support.microsoft.com/zh-cn/kb/315968 如何 ︰ 执行批量更新和插入使用.NET 提供程序在 C#.NET OpenXML Email Prin ...

随机推荐

  1. [SQL in Azure] Provisioning a SQL Server Virtual Machine on Azure

    http://azure.microsoft.com/en-us/documentation/articles/virtual-machines-provision-sql-server/ Provi ...

  2. 数据库记录锁表锁实际研究笔记 --- MSSQLSERVER

    直切主题 现有一张表 table : ChenJi ID, DanWeiID,  Name,  ChenJi 表中记录 ID  DanWeiID    Name      ChenJi --- --- ...

  3. Spark SQL利器:cacheTable/uncacheTable【转】

    转自:http://www.cnblogs.com/yurunmiao/p/4936583.html Spark相对于Hadoop MapReduce有一个很显著的特性就是“迭代计算”(作为一个Map ...

  4. 【Delphi】SPComm注意事项

    Spcomm属性设置 SPCOMM 控件的属性设置很关键的,特别是使用事件驱动时接收大数据块时尤为明显,如果设置不当,接收到的数据可能严重出错. ReadIntervalTimeout:=100 SP ...

  5. mybatis逆向工程自动生成实体类、接口以及映射Mapper.xml配置文件

    Mybatis的逆向工程非常简单,只要一个配置文件和一个Main方法就可以实现,下面以maven工程为例: (1)在pom.xml中引入依赖包 <dependency> <group ...

  6. 在CentOS6.5上安装/启动PostgreSQL

    CentOS install PostgreSQL yum install postgresql-server Start PostgreSQL service postgresql initdb # ...

  7. LeetCode: Reverse Integer 解题报告

    Reverse Integer Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, retur ...

  8. Wince/VC高效PNG贴图,自定义Alpha算法

    工作中,做一些炫点的界面都需要用到PNG图片,Wince里面微软也提供了PNG图片的支持,不过Alpha的混合速度比较慢,所以自己实现了一个Alpha的混合运算接口,经过测试,要比微软AlphaBle ...

  9. 2017 码云最火爆开源项目 TOP 50,你都用过哪些

    本文转自:https://share.html5.qq.com/fx/u?r=JdjvzwC 2017 年度码云热门项目排行榜 TOP 50 出炉啦!我们根据所有开源项目在码云的用户关注度.活跃度.访 ...

  10. android开发——从相冊中选择图片不裁剪

    转载请注明出处:http://blog.csdn.net/zhoubin1992/article/details/46864777 问题: 在郭神的第一行代码中,第8章的从相冊中选择图片这块,从相冊选 ...