execute Batch SQL - Java JDBC

Java examples for JDBC:Batch SQL

Description

execute Batch SQL

Demo Code


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import org.apache.log4j.Logger;

public class Main{
    private static Logger logger = Logger.getLogger(JdbcUtil.class);
    public static void executeBatchSQL(Connection conn, List<String> sqlList)
            throws SQLException {
        Statement stmt = null;//from  w  w  w.ja v  a2  s.  co  m
        try {
            stmt = conn.createStatement();
            for (String sql : sqlList) {
                stmt.addBatch(sql);
            }
            stmt.executeBatch();
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
    }
    public static void close(ResultSet rs) throws SQLException {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                logger.error(e.getMessage(), e);
                throw e;
            }
        }
    }
    public static void close(Statement stmt) throws SQLException {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                logger.error(e.getMessage(), e);
                throw e;
            }
        }
    }
    public static void close(Connection connection) throws SQLException {
        if (connection != null && !connection.isClosed()) {
            try {
                connection.close();
            } catch (SQLException e) {
                logger.error("", e);
                throw e;
            }
        }
    }
    public static void close(Connection connection, Statement stmt,
            ResultSet rs) throws SQLException {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                logger.error(e.getMessage(), e);
                throw e;
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                logger.error(e.getMessage(), e);
                throw e;
            }
        }
        if (connection != null && !connection.isClosed()) {
            try {
                connection.close();
            } catch (SQLException e) {
                logger.error(e.getMessage(), e);
                throw e;
            }
        }
    }
}

Related Tutorials