Example usage for java.sql PreparedStatement addBatch

List of usage examples for java.sql PreparedStatement addBatch

Introduction

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

Prototype

void addBatch() throws SQLException;

Source Link

Document

Adds a set of parameters to this PreparedStatement object's batch of commands.

Usage

From source file:org.wso2.carbon.device.mgt.mobile.impl.windows.dao.impl.WindowsFeatureDAOImpl.java

@Override
public boolean addFeatures(List<MobileFeature> mobileFeatures) throws MobileDeviceManagementDAOException {
    PreparedStatement stmt = null;
    boolean status = false;
    Connection conn;//from   w  w  w  . j a  va 2s  .  c o m
    try {
        conn = WindowsDAOFactory.getConnection();
        stmt = conn.prepareStatement("INSERT INTO WIN_FEATURE(CODE, NAME, DESCRIPTION) VALUES (?, ?, ?)");
        for (MobileFeature mobileFeature : mobileFeatures) {
            stmt.setString(1, mobileFeature.getCode());
            stmt.setString(2, mobileFeature.getName());
            stmt.setString(3, mobileFeature.getDescription());
            stmt.addBatch();
        }
        stmt.executeBatch();
        status = true;
    } catch (SQLException e) {
        throw new WindowsFeatureManagementDAOException(
                "Error occurred while adding windows features into the metadata repository", e);
    } finally {
        MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
    }
    return status;
}

From source file:org.opencron.server.dao.HibernateDao.java

@Transactional(readOnly = false)
public void executeBatch(final String sql, final Object[]... parameters) {
    getSession().doWork(new Work() {

        public void execute(Connection connection) throws SQLException {
            connection.setAutoCommit(false);
            PreparedStatement stmt = connection.prepareStatement(sql);
            for (Object[] arr : parameters) {
                int i = 1;
                for (Object p : arr) {
                    stmt.setObject(i++, p);
                }/*from ww  w  .j av a  2s .c  om*/
                stmt.addBatch();
            }
            stmt.executeBatch();
            connection.commit();
        }
    });
}

From source file:org.schedoscope.metascope.tasks.repository.mysql.impl.ViewEntityMySQLRepository.java

public void updateStatus(Connection connection, Set<ViewEntity> views) {
    String updateStatus = "update view_entity set status=?, transformation_start=?, transformation_end=? where url_path = ?";
    PreparedStatement updateStatusStmt = null;
    try {/*from w ww  . java2 s  .  c  o m*/
        int updateStatusBatch = 0;
        connection.setAutoCommit(false);
        updateStatusStmt = connection.prepareStatement(updateStatus);
        for (ViewEntity viewEntity : views) {
            updateStatusStmt.setString(1, viewEntity.getStatus());
            updateStatusStmt.setLong(2, viewEntity.getTransformationStart());
            updateStatusStmt.setLong(3, viewEntity.getTransformationEnd());
            updateStatusStmt.setString(4, viewEntity.getUrlPath());
            updateStatusStmt.addBatch();
            updateStatusBatch++;
            if (updateStatusBatch % 1000 == 0) {
                updateStatusStmt.executeBatch();
            }
        }
        updateStatusStmt.executeBatch();
        connection.commit();
        connection.setAutoCommit(true);
    } catch (SQLException e) {
        LOG.error("Could not update view", e);
    } finally {
        DbUtils.closeQuietly(updateStatusStmt);
    }
}

From source file:org.eclipse.scada.ds.storage.jdbc.internal.JdbcStorageDaoBase64Impl.java

protected void insertNode(final ConnectionContext connectionContext, final DataNode node, final String data)
        throws SQLException {
    if (data == null) {
        return;/* ww  w . j av a2 s .  com*/
    }

    final PreparedStatement stmt = connectionContext.getConnection().prepareStatement(SQL_INSERT);

    final int len = data.length();

    for (int i = 0; i <= len / this.chunkSize; i++) {
        int end = (i + 1) * this.chunkSize;
        if (end > len) {
            end = len;
        }

        final String chunk = data.substring(i * this.chunkSize, end);

        stmt.setObject(1, node.getId());
        stmt.setObject(2, this.instanceId);
        stmt.setObject(3, i);
        stmt.setObject(4, chunk);
        stmt.addBatch();
    }

    stmt.executeBatch();
}

From source file:iddb.runtime.db.model.dao.impl.mysql.PenaltyDAOImpl.java

@Override
public void disable(List<Penalty> list) {
    String sql = "update penalty set active = ? where id = ?";
    Connection conn = null;/*w ww  .j  a v  a2s. co m*/
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql);
        for (Penalty p : list) {
            st.setBoolean(1, false);
            st.setLong(2, p.getKey());
            st.addBatch();
        }
        st.executeBatch();
    } catch (SQLException e) {
        logger.error("disable: {}", e);
    } catch (IOException e) {
        logger.error("disable: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.batoo.jpa.core.impl.jdbc.dbutils.QueryRunner.java

/**
 * Calls update after checking the parameters to ensure nothing is null.
 * //from ww w  .  ja  v  a 2  s . c o  m
 * @param conn
 *            The connection to use for the batch call.
 * @param closeConn
 *            True if the connection should be closed, false otherwise.
 * @param sql
 *            The SQL statement to execute.
 * @param params
 *            An array of query replacement parameters. Each row in this array is one set of batch replacement values.
 * @return The number of rows updated in the batch.
 * @throws SQLException
 *             If there are database or parameter errors.
 */
private int[] batch(Connection conn, boolean closeConn, String sql, Object[][] params) throws SQLException {
    if (conn == null) {
        throw new SQLException("Null connection");
    }

    if (sql == null) {
        if (closeConn) {
            this.close(conn);
        }
        throw new SQLException("Null SQL statement");
    }

    if (params == null) {
        if (closeConn) {
            this.close(conn);
        }
        throw new SQLException("Null parameters. If parameters aren't need, pass an empty array.");
    }

    PreparedStatement stmt = null;
    int[] rows = null;
    try {
        stmt = this.prepareStatement(conn, sql);

        for (final Object[] param : params) {
            this.fillStatement(stmt, param);
            stmt.addBatch();
        }
        rows = stmt.executeBatch();

    } catch (final SQLException e) {
        this.rethrow(e, sql, (Object[]) params);
    } finally {
        this.close(stmt);
        if (closeConn) {
            this.close(conn);
        }
    }

    return rows;
}

From source file:com.chenxin.authority.common.logback.DBAppender.java

@SuppressWarnings("rawtypes")
protected void insertProperties(Map<String, String> mergedMap, Connection connection, long eventId)
        throws SQLException {
    Set propertiesKeys = mergedMap.keySet();
    // TODO:add chenxin ?logging_event_property
    if (propertiesKeys.size() < -1) {
        PreparedStatement insertPropertiesStatement = connection.prepareStatement(insertPropertiesSQL);

        for (Iterator i = propertiesKeys.iterator(); i.hasNext();) {
            String key = (String) i.next();
            String value = mergedMap.get(key);

            insertPropertiesStatement.setLong(1, eventId);
            insertPropertiesStatement.setString(2, key);
            insertPropertiesStatement.setString(3, value);

            if (cnxSupportsBatchUpdates) {
                insertPropertiesStatement.addBatch();
            } else {
                insertPropertiesStatement.execute();
            }//from   w w  w . j  ava2s.c  o  m
        }

        if (cnxSupportsBatchUpdates) {
            insertPropertiesStatement.executeBatch();
        }

        insertPropertiesStatement.close();
        insertPropertiesStatement = null;
    }
}

From source file:info.naiv.lab.java.tool.sqlite.exporter.component.DataAccess.java

/**
 *
 * @param sourceTempl/*from   w  w w .  j a v a 2s .  c  o  m*/
 * @param destTempl
 * @param info
 * @param valueHandler
 */
public void copy(final JdbcTemplate sourceTempl, JdbcTemplate destTempl, TableInfo info,
        final ValueHandler valueHandler) {

    final Query sq = selectTables.merge(info);

    Query q = insertSql.merge(info);
    final List<Field> fields = info.getFields();
    q.execute(destTempl, new PreparedStatementCallback<Void>() {

        @Override
        public Void doInPreparedStatement(final PreparedStatement ps) throws SQLException, DataAccessException {
            ps.getConnection().setAutoCommit(false);
            try {
                List<Integer> list = sq.query(sourceTempl, new RowMapper<Integer>() {

                    @Override
                    public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
                        int col = 1;
                        for (Field field : fields) {
                            Object val = valueHandler.handleValue(field, rs);
                            ps.setObject(col, val);
                        }
                        ps.addBatch();
                        if (rowNum % BATCH_SIZE == 0) {
                            logger.info("execBatch: {}", rowNum);
                            ps.executeBatch();
                        }
                        return rowNum;
                    }
                });

                int total = list.size();
                logger.info("total Batch: {}", total);
                if (total % BATCH_SIZE != 0) {
                    ps.executeBatch();
                }
                ps.getConnection().commit();
            } catch (SQLException | RuntimeException e) {
                ps.getConnection().rollback();
                throw e;
            }
            return null;
        }
    });
}

From source file:com.glaf.base.test.service.MxMixFeatureTestService.java

@Transactional
public void run() {
    log.debug("-------------------start run-------------------");
    for (int i = 0; i < 2; i++) {
        SysLog bean = new SysLog();
        bean.setAccount("test");
        bean.setIp("127.0.0.1");
        bean.setOperate("add");
        sysLogService.create(bean);/*from   www  .j a va2 s . com*/
    }

    String sql = "insert into SYS_LOG(ID, ACCOUNT, IP, CREATETIME, MODULEID, OPERATE, FLAG, TIMEMS) values (?, ?, ?, ?, ?, ?, ?, ?) ";
    Connection connection = null;
    PreparedStatement psmt = null;
    try {
        connection = DataSourceUtils.getConnection(jdbcTemplate.getDataSource());
        System.out.println("connection:" + connection.toString());
        psmt = connection.prepareStatement(sql);
        for (int i = 0; i < 2; i++) {
            psmt.setLong(1, idGenerator.nextId());
            psmt.setString(2, "test2");
            psmt.setString(3, "192.168.0.100");
            psmt.setTimestamp(4, DateUtils.toTimestamp(new Date()));
            psmt.setString(5, "xx");
            psmt.setString(6, "Y");
            psmt.setInt(7, 1);
            psmt.setLong(8, i * i);
            psmt.addBatch();
        }
        psmt.executeBatch();
        psmt.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error(ex);
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
    }
    log.debug("-------------------end run-------------------");
}

From source file:com.github.tosdan.utils.sql.MyQueryRunner.java

/**
* Calls update after checking the parameters to ensure nothing is null.
* @param conn The connection to use for the batch call.
* @param closeConn True if the connection should be closed, false otherwise.
* @param sql The SQL statement to execute.
* @param params An array of query replacement parameters.  Each row in
* this array is one set of batch replacement values.
* @return The number of rows updated in the batch.
* @throws SQLException If there are database or parameter errors.
*//* w  w w.  ja  v a 2s.c  o  m*/
private int[] batch(Connection conn, boolean closeConn, String sql, Object[][] params) throws SQLException {
    if (conn == null) {
        throw new SQLException("Null connection");
    }

    if (sql == null) {
        if (closeConn) {
            close(conn);
        }
        throw new SQLException("Null SQL statement");
    }

    if (params == null) {
        if (closeConn) {
            close(conn);
        }
        throw new SQLException("Null parameters. If parameters aren't need, pass an empty array.");
    }

    PreparedStatement stmt = null;
    int[] rows = null;
    try {
        stmt = this.prepareStatement(conn, sql);

        for (int i = 0; i < params.length; i++) {
            this.fillStatement(stmt, params[i]);
            stmt.addBatch();
        }
        rows = stmt.executeBatch();

    } catch (SQLException e) {
        this.rethrow(e, sql, (Object[]) params);
    } finally {
        close(stmt);
        if (closeConn) {
            close(conn);
        }
    }

    return rows;
}