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

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

原文地址:https://www.cnblogs.com/borter/p/9608794.html

时间: 2025-02-01 20:03:50

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

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

以下是使用Statement对象的批处理的典型步骤序列 - 使用createStatement()方法创建Statement对象. 使用setAutoCommit()将自动提交设置为false. 使用addBatch()方法在创建的Statement对象上添加SQL语句到批处理中. 在创建的Statement对象上使用executeBatch()方法执行所有SQL语句. 最后,使用commit()方法提交所有更改. 此示例代码是基于前面章节中完成的环境和数据库设置编写的. 以下代码片段提供了使用

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

一.Java的反射机制   每个Java程序执行前都必须经过编译.加载.连接.和初始化这几个阶段,后三个阶段如下图:  其中 i.加载是指将编译后的java类文件(也就是.class文件)中的二进制数据读入内存,并将其放在运行时数据区的方法区内,然后再堆区创建一个Java.lang.Class对象,用来封装类在方法区的数据结构.即加载后最终得到的是Class对象,并且更加值得注意的是:该Java.lang.Class对象是单实例的,无论这个类创建了多少个对象,他的Class对象时唯一的!!!!.

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

用JDBC编程的执行时错误及其解决 用JDBC编程的执行时错误及其解决 源码: 1.java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver 1.1 错误信息: 1.2 错误描写叙述 1.3 错误解决方法 2.用户 'sa' 登录失败 2.1 错误信息: 2.2 错误描写叙述 2.3 错误解决方法 3.Invalid parameter binding(s) 3.1 错误信息: 3.2 错误描写叙

(一)Python入门-6面向对象编程:02类的定义-类和对象的关系-构造函数-实例属性-实例方法

一:类的定义 如果把对象比作一个“饼干”,类就是制造这个饼干的“模具”. 我们通过类定义数据类型的属性(数据)和方法(行为),也就是说,“类将行为和状态打 包在一起”. 对象是类的具体实体,一般称为“类的实例”.类看做“饼干模具”,对象就是根据这个“模 具”制造出的“饼干”. 从一个类创建对象时,每个对象会共享这个类的行为(类中定义的方法),但会有自己的属 性值(不共享状态).更具体一点:“方法代码是共享的,属性数据不共享”. Python中,“一切皆对象”.类也称为“类对象”,类的实例也称为“

JavaScript中创建字典对象(dictionary)实例

这篇文章主要介绍了JavaScript中创建字典对象(dictionary)实例,本文直接给出了实现的源码,并给出了使用示例,需要的朋友可以参考下 对于JavaScript来说,其自身的Array对象仅仅是个数组,无法提供通过关键字来获取保存的数据,jQuery源码中提供了一种非常好的方式来解决这个问题,先看一下源码: 复制代码代码如下: function createCache() { var keys = []; function cache(key, value) {  // Use (k

PHP执行批量mysql语句

当有多条mysql语句连起来需要执行,比如 $sqls= "insert table a values(1,2); insert table a values(2,3);" 需要执行的话php中可以使用的方法有三个: mysql_query pdo mysqli 三种方法当sqls语句没有问题的时候都是可以的. 但是 当sql语句是错误的时候会出现问题 第一条sql错误:三个方法都返回false 第一条sql正确,第二条sql错误:mysql_query.pdo. mysqli:que

验证Unity依赖注入的对象是否为同一个实例

在使用Unity的时候,能够很好的解耦,解除层与层之间的依赖性.这里有一个问题,每次向Unity中要对象实例的时候,这时候给出的是同一个吗?还是每次都是new一个新的?我来写代码验证一下.怎么验证两个对象是否为同一个呢,看这个对象在内存中的地址就行了,通过Hash码查看就可以. namespace UnityApplication { public interface IService { string Show(); } } namespace UnityApplication { publi

com.microsoft.sqlserver.jdbc.SQLServerException: 对象名 'xxxxx' 无效

一般这种问题就是由于大家在.hbm.xml定义的数据库表名和数据库的关键字冲突了,导致产生这样的错误.但我今天遇到了下面的错误,看着像是那个问题,不过我整了好久并不是关键字冲突问题,由于是手工配置,在配置时将正确的 hibernate.hbm2ddl.auto=update误写成了hibernate.hbm2ddl=update导致下边的错误,好几个小时就在痛苦中度过了.. Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: 对

Javascript中使用WScript.Shell对象执行.bat文件和cmd命令

Javascript中使用WScript.Shell对象执行.bat文件和cmd命令 http://www.cnblogs.com/ZHF/p/3328439.html WScript.Shell(Windows Script Host Runtime Library)是一个对象,对应的文件是C:/WINDOWS/system32/wshom.ocx,Wscript.shell是服务器系统会用到的一种组件.shell 就是“壳”的意思,这个对象可以执行操作系统外壳常用的操作,比如运行程序.读写注