简体   繁体   English

从 PreparedStatement 列表转换为 PreparedStatement 批处理

[英]Convert from List of preparedStatements to PreparedStatement batch

I have an arrayList of PreparedStatement我有一个 PreparedStatement 的 arrayList

ArrayList<PreparedStatement> prestmtBatchList = new ArrayList<PreparedStatement>();

With time I add a number of preparedStatements in it:随着时间的推移,我在其中添加了许多 PreparedStatement:

PreparedStatement ps = DBUtility.returnInsertQueryAsString("ind_it_decl_sec10log", keysToSaveInLog, itdeclsec10loginfo, con);
                                    if(!ErmUtil.isNull(ps)){
                                        prestmtBatchList.add(ps);
                                    }

I want to execute them at once, hence need to be converted in Batch.我想一次执行它们,因此需要批量转换。 I know it sounds silly to do this.我知道这样做听起来很愚蠢。

Still you want PreparedStatement , place the logic of the function in your PreparedStatement code itself.The below solution will help you.仍然需要 PreparedStatement ,将函数的逻辑放在 PreparedStatement 代码本身中。以下解决方案将对您有所帮助。

conn.setAutoCommit(false);

PreparedStatement ps = //instantiate
pstmt.setInt( 1, 1243);
pstmt.setString( 2, "test" );
pstmt.setString( 3, "test" );
pstmt.setInt( 4, 123 );

ps.addBatch();

pstmt.setInt( 1, 1243);
pstmt.setString( 2, "12334" );
pstmt.setString( 3, "21423" );
pstmt.setInt( 4, 123 );

ps.addBatch();

int[] count = ps.executeBatch();
conn.commit();

For batch execution, you can use Prepared statement's native executeBatch() method.对于批处理执行,您可以使用 Prepared 语句的原生 executeBatch() 方法。 To improve performance of Java database application is running queries with setAutoCommit(false).为了提高 Java 数据库应用程序的性能,使用 setAutoCommit(false) 运行查询。 By default new JDBC connection has there auto commit mode ON, which means every individual SQL Statement will be executed in its own transaction.默认情况下,新的 JDBC 连接具有自动提交模式,这意味着每个单独的 SQL 语句都将在其自己的事务中执行。 while without auto commit you can group SQL statement into logical transaction, which can either be committed or rolled back by calling commit() or rollback().而没有自动提交,您可以将 SQL 语句分组为逻辑事务,可以通过调用 commit() 或 rollback() 提交或回滚。

Below code explains further :-下面的代码进一步解释:-

PreparedStatement preparedStatement = null;
            preparedStatement = dbConnection.prepareStatement(insertTableSQL);

            dbConnection.setAutoCommit(false);

            preparedStatement.setInt(1, 101);
            preparedStatement.setString(2, "test1");
            preparedStatement.addBatch();

            preparedStatement.setInt(1, 102);
            preparedStatement.setString(2, "test2");
            preparedStatement.addBatch();

            preparedStatement.setInt(1, 103);
            preparedStatement.setString(2, "test3");
            preparedStatement.addBatch();

            preparedStatement.executeBatch();

            dbConnection.commit();

instead doubting one's help better suggest solutions.而不是怀疑自己的帮助更好地提出解决方案。 Anyways enjoy the whole class.无论如何享受整个课堂。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package test;

/**
 *
 * @author vaibhav.kashyap
 */


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

public class PreparedBatchJDBC {

    private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/mydb";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "root";

    public static void main(String[] argv) {

        try {

            batchInsertRecordsIntoTable();

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        }

    }

    private static void batchInsertRecordsIntoTable() throws SQLException {

        Connection dbConnection = null;
        PreparedStatement preparedStatement = null;

        String insertTableSQL = "INSERT INTO DBUSER"
                + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
                + "(?,?,?,?)";

        try {
            dbConnection = getDBConnection();
            preparedStatement = dbConnection.prepareStatement(insertTableSQL);

            dbConnection.setAutoCommit(false);

            preparedStatement.setInt(1, 101);
            preparedStatement.setString(2, "test1");
            preparedStatement.setString(3, "system");
            preparedStatement.setTimestamp(4, getCurrentTimeStamp());
            preparedStatement.addBatch();

            preparedStatement.setInt(1, 102);
            preparedStatement.setString(2, "test2");
            preparedStatement.setString(3, "system");
            preparedStatement.setTimestamp(4, getCurrentTimeStamp());
            preparedStatement.addBatch();

            preparedStatement.setInt(1, 103);
            preparedStatement.setString(2, "test3");
            preparedStatement.setString(3, "system");
            preparedStatement.setTimestamp(4, getCurrentTimeStamp());
            preparedStatement.addBatch();

            preparedStatement.executeBatch();

            dbConnection.commit();

            System.out.println("Record is inserted into DBUSER table!");

        } catch (SQLException e) {

            System.out.println(e.getMessage());
            dbConnection.rollback();

        } finally {

            if (preparedStatement != null) {
                preparedStatement.close();
            }

            if (dbConnection != null) {
                dbConnection.close();
            }

        }

    }

    private static Connection getDBConnection() {

        Connection dbConnection = null;

        try {

            Class.forName(DB_DRIVER);

        } catch (ClassNotFoundException e) {

            System.out.println(e.getMessage());

        }

        try {

            dbConnection = DriverManager.getConnection(
                              DB_CONNECTION, DB_USER,DB_PASSWORD);
            return dbConnection;

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        }

        return dbConnection;

    }

    private static java.sql.Timestamp getCurrentTimeStamp() {

        java.util.Date today = new java.util.Date();
        return new java.sql.Timestamp(today.getTime());

    }

}

Hope this would help too.希望这也会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM