• JDBC中的批处理


    以下内容引用自http://wiki.jikexueyuan.com/project/jdbc/batch-processing.html

    批处理是指将关联的SQL语句组合成一个批处理,并将他们当成一个调用提交给数据库。

    当一次发送多个SQL语句到数据库时,可以减少通信的资源消耗,从而提高了性能。

    • JDBC驱动程序不一定支持该功能。可以使用DatabaseMetaData.supportsBatchUpdates()方法来确定目标数据库是否支持批处理更新。如果JDBC驱动程序支持此功能,则该方法返回值为true。

    • Statement,PreparedStatement和CallableStatement的addBatch()方法用于添加单个语句到批处理。

    • executeBatch()方法用于启动执行所有组合在一起的语句。

    • executeBatch()方法返回一个整数数组,数组中的每个元素代表了各自的更新语句的更新数目。

    • 正如可以添加语句到批处理中,也可以用clearBatch()方法删除它们。此方法删除所有用addBatch()方法添加的语句。但是,不能有选择性地选择要删除的语句。

    一、批处理和Statement对象

    使用Statement对象来使用批处理所需要的典型步骤如下所示:

    • 使用createStatement()方法创建一个Statement对象。
    • 使用setAutoCommit()方法将自动提交设为false。
    • 被创建的Statement对象可以使用addBatch()方法来添加想要的所有SQL语句。
    • 被创建的Statement对象可以用executeBatch()将所有的SQL语句执行。
    • 最后,使用commit()方法提交所有的更改。

    示例:

    下面的代码段提供了一个使用Statement对象批量更新的例子:

    // Create statement object
    Statement stmt = conn.createStatement();
    
    // Set auto-commit to false
    conn.setAutoCommit(false);
    
    // Create SQL statement
    String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(200,'Zia', 'Ali', 30)";
    // Add above SQL statement in the batch.
    stmt.addBatch(SQL);
    
    // Create one more SQL statement
    String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(201,'Raj', 'Kumar', 35)";
    // Add above SQL statement in the batch.
    stmt.addBatch(SQL);
    
    // Create one more SQL statement
    String 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();

    二、批处理和PrepareStatement对象

    使用PrepareStatement对象来使用批处理需要的典型步骤如下所示:

    • 使用占位符创建SQL语句。
    • 使用任一prepareStatement()方法创建PrepareStatement对象。
    • 使用setAutoCommit()方法将自动提交设为false。
    • 被创建的Statement对象可以使用addBatch()方法来添加想要的所有SQL语句。
    • 被创建的Statement对象可以用executeBatch()将所有的SQL语句执行。
    • 最后,使用commit()方法提交所有的更改。

    下面的代码段提供了一个使用PrepareStatement对象批量更新的示例:

    // Create SQL statement
    String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(?, ?, ?, ?)";
    
    // Create PrepareStatement object
    PreparedStatemen pstmt = conn.prepareStatement(SQL);
    
    //Set auto-commit to false
    conn.setAutoCommit(false);
    
    // Set the variables
    pstmt.setInt( 1, 400 );
    pstmt.setString( 2, "Pappu" );
    pstmt.setString( 3, "Singh" );
    pstmt.setInt( 4, 33 );
    // Add it to the batch
    pstmt.addBatch();
    
    // Set the variables
    pstmt.setInt( 1, 401 );
    pstmt.setString( 2, "Pawan" );
    pstmt.setString( 3, "Singh" );
    pstmt.setInt( 4, 31 );
    // Add it to the batch
    pstmt.addBatch();
    
    //add more batches
    .
    .
    .
    .
    //Create an int[] to hold returned values
    int[] count = stmt.executeBatch();
    
    //Explicitly commit statements to apply changes
    conn.commit();

    示例:

    //Import required packages
    import java.sql.*;
    
    public class JDBCExample {
        // JDBC driver name and database URL
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL = "jdbc:mysql://localhost/Test?serverTimezone=UTC";
    
        // Database credentials
        static final String USER = "root";
        static final String PASS = "root";
    
        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, "Pappu");
                stmt.setString(3, "Singh");
                stmt.setInt(4, 33);
                // Add it to the batch
                stmt.addBatch();
    
                // Set the variables
                stmt.setInt(1, 401);
                stmt.setString(2, "Pawan");
                stmt.setString(3, "Singh");
                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

    这将产生如下所示结果:

    测试工程:https://github.com/easonjim/5_java_example/tree/master/jdbcbasics/test7

  • 相关阅读:
    LR(0)分析法
    算符优先法之优先表构造
    自上而下的LL(1)语法分析法
    K倍区间
    全排列
    mysql自动获取时间日期
    限制
    JQuery
    LinQ 组合查询与分页
    LinQ 简单使用
  • 原文地址:https://www.cnblogs.com/EasonJim/p/6996782.html
Copyright © 2020-2023  润新知