Example usage for java.sql Statement addBatch

List of usage examples for java.sql Statement addBatch

Introduction

In this page you can find the example usage for java.sql Statement addBatch.

Prototype

void addBatch(String sql) throws SQLException;

Source Link

Document

Adds the given SQL command to the current list of commands for this Statement object.

Usage

From source file:com.dbmojo.QueryExecutor.java

/** Add a batch update to either a single statement, the correct
  * passed prepared statement.//from  w  w w. j  a  va2s .c om
  */
private void addBatchUpdate(Connection conn, boolean prepared, String query, String[] values, Statement bstmt,
        LinkedHashMap<String, PreparedStatement> bpstmts) throws Exception {

    //If this is NOT a prepared statement then add the query to a raw SQL batch
    if (!prepared) {
        if (DebugLog.enabled) {
            DebugLog.add(this, "Adding update '" + query + "' to statement batch");
        }
        bstmt.addBatch(query);
    } else {
        //If this IS a prepared statement then check for its existence
        //in the pstmts hash. If it doesn't exist then create a new
        //pstmt for the query and add it to the hash.
        PreparedStatement pstmt = null;
        if (bpstmts.containsKey(query)) {
            if (DebugLog.enabled) {
                DebugLog.add(this, "Retrieving pstmt batch for query '" + query + "'");
            }
            pstmt = bpstmts.get(query);
        } else {
            if (DebugLog.enabled) {
                DebugLog.add(this, "Starting pstmt batch for query '" + query + "'");
            }

            pstmt = conn.prepareStatement(query);
        }

        if (DebugLog.enabled) {
            DebugLog.add(this, "Setting vals on pstmt batch for query '" + query + "'");
        }

        setPreparedStatementValues(pstmt, values);

        //Add THIS set of values to the batch for this specific 
        //prepared statement. Later on all prepared statment batches
        //will be executed sequentially
        if (DebugLog.enabled) {
            DebugLog.add(this, "Adding to pstmt batch for query '" + query + "'");
        }
        pstmt.addBatch();
        bpstmts.put(query, pstmt);
    }
}

From source file:com.npstrandberg.simplemq.MessageQueueImp.java

public boolean delete(List<Message> messages) {

    try {/*w  w w.j  av  a 2s  .  c om*/
        conn.setAutoCommit(false);
        Statement stmt = conn.createStatement();

        for (Message message : messages) {
            if (!(message instanceof MessageWrapper)) {
                throw new IllegalArgumentException("This instance of 'Message' is not valid.");
            }

            stmt.addBatch("DELETE FROM message WHERE id=" + message.getId());
        }

        int[] updateCounts = stmt.executeBatch();

        // Have we deleted them all
        if (updateCounts.length == messages.size()) {
            return true;
        } else {
            logger.error("Not all Messages was deleted! Only " + updateCounts.length + " out of "
                    + messages.size() + " msg was deleted!");
        }

    } catch (SQLException e) {
        logger.error(e);
    } finally {
        try {
            conn.setAutoCommit(true);
        } catch (SQLException e) {
            logger.error(e);
        }
    }

    return false;
}

From source file:com.china317.gmmp.gmmp_report_analysis.App.java

private static void DgmFobbidenStoreIntoDB(Map<String, DgmForbidden> map, ApplicationContext context) {
    /**// w ww.  j  a  v a 2s .  c o m
     * INSERT INTO TAB_GPSEVENT_AREA SELECT
     * CODE,ALARMTYPE,BEGINTIME,ENDTIME,'' FROM ALARMFOBBIDEN_REA
     */
    Connection conn = null;
    String sql = "";
    try {

        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientDgm");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            DgmForbidden pos = map.get(key);
            /*
             * String sql = "insert into ALARMFOBBIDEN_REA " +
             * " (CODE,LICENSE,LICENSECOLOR,ALARMTYPE,BEGINTIME,ENDTIME) " +
             * " values (" + "'" + pos.getCode() + "'," + "'" +
             * pos.getLicense() + "'," + "'" + pos.getLicenseColor() + "',"
             * + "'" + pos.getAlarmType() + "'," + "'" + pos.getBeginTime()
             * + "','" + pos.getEndTime() + "')";
             */
            sql = "insert into TAB_GPSEVENT_AREA " + " (VID,TYPE,BEGIN_TIME,END_TIME,DETAIL) " + " values ("
                    + "'" + pos.getCode() + "'," + "'" + pos.getAlarmType() + "'," + "'" + pos.getBeginTime()
                    + "'," + "'" + pos.getEndTime() + "'," + "'" + "')";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB DgmForbidden success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        DgmAnalysisImp.getInstance().getForbiddeningMap().clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.kuali.kpme.core.util.DatabaseCleanupDataLifecycle.java

public void loadData(final PlatformTransactionManager transactionManager, final DataSource dataSource,
        final String schemaName) {
    Assert.assertNotNull("DataSource could not be located.", dataSource);

    if (schemaName == null || schemaName.equals("")) {
        Assert.fail("Empty schema name given");
    }//from  ww w  .ja  v a  2  s .c o m
    new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
        public Object doInTransaction(final TransactionStatus status) {
            verifyTestEnvironment(dataSource);
            return new JdbcTemplate(dataSource).execute(new StatementCallback() {
                public Object doInStatement(Statement statement) throws SQLException {
                    List<String> sqlStatements = new ArrayList<String>();
                    //
                    // djunk - add a per-class special test data loader,
                    // loads <testclassname>.sql from the same directory
                    // as the other SQL loaded.
                    if (callingTestClass != null) {
                        sqlStatements.addAll(getTestDataSQLStatements(
                                "src/test/config/sql/" + callingTestClass.getSimpleName() + "-cleanup.sql"));
                    }
                    for (String sql : sqlStatements) {
                        if (!sql.startsWith("#") && !sql.startsWith("//") && !StringUtils.isEmpty(sql.trim())) {
                            // ignore comment lines in our sql reader.
                            statement.addBatch(sql);
                        }
                    }
                    statement.executeBatch();
                    return null;
                }
            });
        }
    });
}

From source file:com.china317.gmmp.gmmp_report_analysis.App.java

private static void DgmIllegalParkingStoreIntoDB(Map<String, DgmIllegalParking> map,
        ApplicationContext context) {/*from   ww w. j  a  va2s. c  o  m*/
    /*
     * INSERT INTO TAB_GPSEVENT_ILLEGALPARKING SELECT
     * CODE,'illegalParking',BEGIN_TIME,END_TIME,'',FLAG FROM
     * ALARMILLEGALPARKING_REA
     */
    Connection conn = null;
    String sql = "";
    try {

        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientDgm");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            DgmIllegalParking pos = map.get(key);
            /*
             * String sql = "insert into TAB_GPSEVENT_ILLEGALPARKING " +
             * " (CODE,LICENSE,TYPE,BEGINTIME,ENDTIME,FLAG) " + " values ("
             * + "'" + pos.getCode() + "'," + "'" + pos.getLicense() + "',"
             * + "'" + pos.getType() + "'," + "'" + pos.getBeginTime() +
             * "'," + "'" + pos.getEndTime() + "','" + pos.getFlag() + "')";
             */
            sql = "insert into TAB_GPSEVENT_ILLEGALPARKING " + " (VID,TYPE,BEGIN_TIME,END_TIME,DETAIL,IS_END) "
                    + " values (" + "'" + pos.getCode() + "'," + "'" + pos.getType() + "'," + "'"
                    + pos.getBeginTime() + "'," + "'" + pos.getEndTime() + "'," + "'" + "'," + pos.getFlag()
                    + ")";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB DgmIllegalParking success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        DgmAnalysisImp.getInstance().getIllegalParking().clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.china317.gmmp.gmmp_report_analysis.App.java

private static void DgmEntryExitStoreIntoDB(Map<String, DgmEntryExit> map, ApplicationContext context) {
    /**//w  w  w .  ja  v a2s  .  com
     * INSERT INTO TAB_GPSEVENT_ILLEGALENTRYEXIT SELECT
     * CODE,'illegalEntryExit',BEGIN_TIME,END_TIME,DETAIL,ROAD FROM
     * ALARMILLEGALEXIT_REA
     */
    String sql = "";
    Connection conn = null;
    try {

        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientDgm");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            DgmEntryExit pos = map.get(key);
            /*
             * String sql = "insert into ALARMILLEGALEXIT_REA " +
             * " (CODE,TYPE,BEGIN_TIME,END_TIME,DETAIL,ROAD) " + " values ("
             * + "'" + pos.getCode() + "'," + "'" + pos.getType() + "'," +
             * "'" + pos.getBegin_time() + "'," + "'" + pos.getEnd_time() +
             * "'," + "'" + pos.getDetail() + "','" + pos.getRoad() + "')";
             */
            sql = "insert into TAB_GPSEVENT_ILLEGALENTRYEXIT " + " (VID,TYPE,BEGIN_TIME,END_TIME,DETAIL,ROAD) "
                    + " values (" + "'" + pos.getCode() + "'," + "'illegalEntryExit'," + "'"
                    + pos.getBegin_time() + "'," + "'" + pos.getEnd_time() + "'," + "'" + pos.getDetail()
                    + "','" + pos.getRoad() + "')";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB DgmEntryExit success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        DgmAnalysisImp.getInstance().getExitMap().clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.freebxml.omar.server.persistence.rdb.AbstractDAO.java

/**
 * @see org.freebxml.omar.server.persistence.rdb.OMARDAO#insert(org.oasis.ebxml.registry.bindings.rim.UserType, java.sql.Connection, java.util.List, java.util.HashMap)
 *//*  w  w  w.  j  a v a 2  s  . co  m*/
public void insert(List objects) throws RegistryException {
    //Return immediatley if no objects to insert
    if (objects.size() == 0) {
        return;
    }

    //First process any objects that may already exists in persistence layer
    // BHT: OPTIMIZE ME!!!!!!!!!!!!!
    objects = processExistingObjects(objects);

    //Return immediately if no objects to insert
    if (objects.size() == 0) {
        return;
    }

    log.trace(ServerResourceBundle.getInstance().getString("message.InsertingRowsInTable",
            new Object[] { new Integer(objects.size()), getTableName() }));
    action = DAO_ACTION_INSERT;

    Statement stmt = null;
    try {
        stmt = context.getConnection().createStatement();

        Iterator iter = objects.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();

            String str = getSQLStatementFragment(obj);
            log.trace("SQL = " + str);
            stmt.addBatch(str);

            // HIEOS/BHT (Added block to get rid of MySQL performance bug with DB views).
            String mirrorImageStr = this.getSQLStatementFragmentForMirrorImage(obj);
            if (mirrorImageStr != null) {
                log.trace("SQL = " + mirrorImageStr); // HIEOS/BHT (DEBUG)
                stmt.addBatch(mirrorImageStr); // Now, insert into the mirror.
            }

            prepareToInsert(obj);
        }
        long startTime = System.currentTimeMillis();
        log.trace("AbstractDAO.insert: doing executeBatch");
        int[] updateCounts = stmt.executeBatch();
        long endTime = System.currentTimeMillis();
        log.trace("AbstractDAO.insert: done executeBatch elapedTimeMillis=" + (endTime - startTime));
        iter = objects.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();
            onInsert(obj);
        }

    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } finally {
        closeStatement(stmt);
    }
}

From source file:org.freebxml.omar.server.persistence.rdb.EmailAddressDAO.java

/**
 * Does a bulk update of a Collection of objects that match the type for this persister.
 *
 *//* w ww  . j a va2  s  . c o  m*/
public void update(String parentId, List emailAddresss) throws RegistryException {
    log.debug(ServerResourceBundle.getInstance().getString("message.UpdatingEmailAddresss",
            new Object[] { new Integer(emailAddresss.size()) }));

    Statement stmt = null;

    try {
        stmt = context.getConnection().createStatement();

        Iterator iter = emailAddresss.iterator();

        while (iter.hasNext()) {
            EmailAddress emailAddress = (EmailAddress) iter.next();

            String address = emailAddress.getAddress();

            String type = emailAddress.getType();

            if (type != null) {
                type = "'" + type + "'";
            }

            String str = "UPDATE EmailAddress SET " +
            //"accesControlPolicy = null, " +
                    "SET address = '" + address + "', " + "SET type = " + type + " WHERE parent = '" + parentId
                    + "' ";
            log.trace("SQL = " + str);
            stmt.addBatch(str);
        }

        stmt.executeBatch();
    } catch (SQLException e) {
        RegistryException exception = new RegistryException(e);
        throw exception;
    } finally {
        closeStatement(stmt);
    }
}

From source file:org.freebxml.omar.server.persistence.rdb.EmailAddressDAO.java

/**
 * Does a bulk insert of a Collection of objects that match the type for this persister.
 *
 *//*from   www. j a v  a2s. c  om*/
public void insert(String parentId, List emailAddresss) throws RegistryException {
    log.debug(ServerResourceBundle.getInstance().getString("message.InsertingEmailAddresss",
            new Object[] { new Integer(emailAddresss.size()) }));

    if (emailAddresss.size() == 0) {
        return;
    }

    Statement stmt = null;

    try {
        stmt = context.getConnection().createStatement();

        Iterator iter = emailAddresss.iterator();

        while (iter.hasNext()) {
            EmailAddressType emailAddress = (EmailAddressType) iter.next();

            //Log.print(Log.TRACE, 8, "\tDATABASE EVENT: storing EmailAddress " );
            String address = emailAddress.getAddress();

            String type = emailAddress.getType();

            if (type != null) {
                type = "'" + type + "'";
            }

            String str = "INSERT INTO EmailAddress " + "VALUES( " + "'" + address + "', " + type + ", " + "'"
                    + parentId + "' )";
            log.trace("SQL = " + str);
            stmt.addBatch(str);
        }

        if (emailAddresss.size() > 0) {
            stmt.executeBatch();
        }
    } catch (SQLException e) {
        RegistryException exception = new RegistryException(e);
        throw exception;
    } finally {
        closeStatement(stmt);
    }
}

From source file:ru.tehkode.permissions.backends.hybrid.HybridBackend.java

private void executeStream(SQLConnection conn, InputStream str) throws SQLException, IOException {
    String deploySQL = StringUtils.readStream(str);

    Statement s = conn.getStatement();

    for (String sqlQuery : deploySQL.trim().split(";")) {
        sqlQuery = sqlQuery.trim();/*from  w  ww. j  ava 2  s .co m*/
        if (sqlQuery.isEmpty()) {
            continue;
        }

        sqlQuery = conn.expandQuery(sqlQuery + ";");

        s.addBatch(sqlQuery);
    }
    s.executeBatch();
}