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.pvalsecc.jdbc.JdbcUtilities.java

public static <T> void runInsertQuery(String description, String sqlStatement, Connection conn,
        Iterator<T> items, int batchSize, InsertTask<T> task) throws SQLException {
    PreparedStatement stmt = null;

    try {/*from w w  w. j a va 2 s.c  o m*/
        long beginTime = System.currentTimeMillis();

        // It's property closed in the finally!
        //noinspection JDBCResourceOpenedButNotSafelyClosed
        stmt = conn.prepareStatement(sqlStatement);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Executing SQL : " + sqlStatement + " (" + description + ")");
        }

        int idx = 0;
        int cpt = 0;
        while (items.hasNext()) {
            T item = items.next();
            if (task.marshall(stmt, item)) {
                stmt.addBatch();

                if (++idx >= batchSize) {
                    stmt.executeBatch();
                    idx = 0;
                }
                ++cpt;
            }
        }

        if (idx > 0) {
            stmt.executeBatch(); // do not forget the last one as usual...
        }
        if (TIMING_LOGGER.isDebugEnabled()) {
            TIMING_LOGGER.debug("Time " + description + " (" + cpt + " records): "
                    + UnitUtilities.toElapsedTime(System.currentTimeMillis() - beginTime));
        }
    } catch (BatchUpdateException ex) {
        LOGGER.error(ex.getNextException());
        throw ex;
    } finally {
        safeClose(stmt);
    }
}

From source file:module.entities.NameFinder.DB.java

public static void InsertJsonLemmas(TreeMap<EntityEntry, Integer> docEntities, int text_id, int jsonKey)
        throws SQLException {
    String insertSQL = "INSERT INTO json_annotated_lemmas "
            + "(lemma_text,lemma_category,lemma_text_id,lemma_jsonKey,lemma_count) VALUES" + "(?,?,?,?,?)";
    PreparedStatement prepStatement = connection.prepareStatement(insertSQL);
    for (Map.Entry<EntityEntry, Integer> ent : docEntities.entrySet()) {

        prepStatement.setString(1, ent.getKey().text);
        prepStatement.setString(2, ent.getKey().category);
        prepStatement.setInt(3, text_id);
        prepStatement.setInt(4, jsonKey);
        prepStatement.setInt(5, ent.getValue().intValue());
        prepStatement.addBatch();
    }//  ww w  .j  a  va 2  s .c om
    prepStatement.executeBatch();
    prepStatement.close();

}

From source file:module.entities.NameFinder.DB.java

public static void insertJsonResponse(int curConsId, TreeMap<Integer, String> input) throws SQLException {
    try {/*from w ww  .  ja va 2 s .c om*/
        String insertSQL = "INSERT INTO enhancedentities " + "(consultation_id,article_id,json_text) VALUES"
                + "(?,?,?);";
        PreparedStatement prepStatement = connection.prepareStatement(insertSQL);
        //            connection.setAutoCommit(false);
        for (int curArticle : input.keySet()) {
            String json_text = input.get(curArticle);
            prepStatement.setInt(1, curConsId);
            prepStatement.setInt(2, curArticle);
            prepStatement.setString(3, json_text);
            //                prepStatement.executeUpdate();
            prepStatement.addBatch();
        }
        prepStatement.executeBatch();
        //            connection.commit();
        prepStatement.close();

        //            for (int i = 0; i<x.length; i++){
        //                System.out.println(x[i]);
        //            }
    } catch (BatchUpdateException ex) {
        ex.printStackTrace();
        //            System.out.println(ex.getNextException());
    }
}

From source file:com.chaosinmotion.securechat.server.commands.DropMessages.java

public static void processRequest(UserInfo userinfo, JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    ArrayList<Message> messages = new ArrayList<Message>();

    JSONArray a = requestParams.getJSONArray("messages");
    int i, len = a.length();
    for (i = 0; i < len; ++i) {
        JSONObject item = a.getJSONObject(i);
        Message msg = new Message();
        msg.message = item.getInt("messageid");
        msg.checksum = item.getString("checksum");
        messages.add(msg);//  w  ww. j  av a2  s.c  o  m
    }

    /*
     * Iterate through the messages, deleting each. We only delete a
     * message if message belongs to the user and the checksum matches.
     * This assumes it's our message and it was read with someone who
     * can read the message.
     * 
     * (Thus, the weird query)
     */

    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        int count = 0;
        c = Database.get();
        ps = c.prepareStatement("DELETE FROM Messages " + "WHERE messageid IN "
                + "    (SELECT Messages.messageid " + "     FROM Messages, Devices "
                + "     WHERE Messages.messageid = ? " + "     AND Messages.checksum = ? "
                + "     AND Devices.deviceid = Messages.deviceid " + "     AND Devices.userid = ?)");

        for (Message msg : messages) {
            /*
             * Get the device ID for this device. Verify it belongs to the
             * user specified
             */

            ps.setInt(1, msg.message);
            ps.setString(2, msg.checksum);
            ps.setInt(3, userinfo.getUserID());
            ps.addBatch();
            ++count;
            if (count > 10240) {
                ps.executeBatch();
            }
        }
        if (count > 0) {
            ps.executeBatch();
        }
    } catch (BatchUpdateException batch) {
        throw batch.getNextException();
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}

From source file:module.entities.NameFinder.DB.java

public static void insertDemocracitConsultationMinister(TreeMap<Integer, String> consultationCountersign,
        TreeMap<Integer, String> consultationCounterrole) throws SQLException {
    try {/*from   ww  w . ja  v  a2  s  .  c o m*/
        String sql = "INSERT INTO consultations_ner "
                + "(id,countersigned_name, countersigned_position) VALUES " + "(?,?,?)";
        PreparedStatement prepStatement = connection.prepareStatement(sql);
        for (int consId : consultationCountersign.keySet()) {
            prepStatement.setInt(1, consId);
            prepStatement.setString(2, consultationCountersign.get(consId));
            if (consultationCounterrole.get(consId) != null) {
                prepStatement.setString(3, consultationCounterrole.get(consId));
            } else {
                prepStatement.setString(3, "");
            }
            prepStatement.addBatch();
        }
        prepStatement.executeBatch();
        prepStatement.close();
    } catch (BatchUpdateException ex) {
        //            ex.printStackTrace();
        System.out.println(ex.getNextException());
    }
}

From source file:com.adaptris.core.services.jdbc.JdbcBatchingDataCaptureService.java

@Override
protected long executeUpdate(PreparedStatement insert) throws SQLException {
    int count = counter.get().incrementAndGet();
    insert.addBatch();
    long rowsUpdated = 0;
    if (count % batchWindow() == 0) {
        log.trace("BatchWindow reached, executeBatch()");
        rowsUpdated = rowsUpdated(insert.executeBatch());
    }/*ww  w. j  a  v  a 2  s . c o  m*/
    return rowsUpdated;
}

From source file:org.apache.lucene.store.jdbc.handler.MarkDeleteFileEntryHandler.java

public List deleteFiles(final List names) throws IOException {
    jdbcTemplate.batchUpdate(table.sqlMarkDeleteByName(), new BatchPreparedStatementSetter() {
        @Override//from   ww w  .j av a  2  s . co m
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setFetchSize(1);
            ps.setBoolean(1, true);
            ps.setString(2, (String) names.get(i));
            ps.addBatch();
        }

        @Override
        public int getBatchSize() {
            return names.size();
        }
    });
    return null;
}

From source file:org.cartoweb.stats.report.DbTestCase.java

protected void addRecord(StatsRecord record) throws SQLException {
    final String query = "INSERT INTO " + TABLE_NAME + " (" + Import.MAPPER.getFieldNames() + ") VALUES ("
            + Import.MAPPER.getInsertPlaceHolders() + ")";
    PreparedStatement stmt = con.prepareStatement(query);

    Import.MAPPER.saveToDb(stmt, record, 1);
    stmt.addBatch();
    stmt.executeBatch();//from  w  w  w.  j a  v  a  2s . co m
    stmt.close();
    con.commit();
}

From source file:com.pactera.edg.am.metamanager.extractor.dao.helper.DeleteDependencyHelper.java

private void doInPreparedStatement(long sysTime, MMDDependency dependency, PreparedStatement ps)
        throws SQLException {
    // ?ID//from www.  j a v  a 2  s . co  m
    ps.setString(1, dependency.getOwnerMetadata().getId());
    // ?ID
    ps.setString(2, dependency.getValueMetadata().getId());

    ps.addBatch();
    ps.clearParameters();

    if (++super.count % super.batchSize == 0) {
        ps.executeBatch();
        ps.clearBatch();
    }
}

From source file:namedatabasescraper.PageScraper.java

public void storeToDb(MainWindow parent) throws SQLException {
    logger.log(Level.INFO, "Started storing names for scraper id {0}", this.dirname);
    Connection conn = NameDatabaseScraper.application.getConnection();
    PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO names VALUES (?, ?)");
    stmt2.setString(2, this.dirname);
    conn.setAutoCommit(false);/*from w  ww .  j  a v  a2  s .c om*/
    for (String name : this.names) {
        stmt2.setString(1, name);
        stmt2.addBatch();
    }
    stmt2.executeBatch();
    conn.setAutoCommit(true);
    logger.log(Level.INFO, "Stored " + this.names.size() + " names for scraper id {0}", this.dirname);
}