Example usage for java.sql PreparedStatement executeBatch

List of usage examples for java.sql PreparedStatement executeBatch

Introduction

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

Prototype

int[] executeBatch() throws SQLException;

Source Link

Document

Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.

Usage

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

public static void InsertLexiconEntry(PreparedStatement statement, String lexiconType, String lemma,
        String entity, String lang) throws SQLException {
    try {/*www. j av  a2 s  . com*/
        statement.setString(1, lexiconType);
        statement.setString(2, lemma);
        statement.setString(3, entity);
        statement.setString(4, lang);
        statement.addBatch();
        batchSize++;
        if (batchSize == 1000) {
            statement.executeBatch();
            statement.clearBatch();
            batchSize = 0;
        }
    } catch (SQLException ex) {
        System.err.println("Skipping:" + lemma + " " + entity + " " + ex.getMessage());
    }
}

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();/* w  w  w . j av  a  2  s  .c o m*/
    }
    prepStatement.executeBatch();
    prepStatement.close();

}

From source file:net.firejack.platform.core.utils.db.DBUtils.java

private static void insertDataToTargetTable(TablesMapping mapping, Connection sourceConnection,
        Connection targetConnection) throws SQLException {
    Map<Column, Column> columnMapping = mapping.getColumnMapping();
    if (columnMapping.isEmpty()) {
        logger.warn("No columns are detected - no data to insert.");
    } else {//from w w  w  .  j  a  va 2  s  . c  o m
        ResultSet rs = selectDataFromSource(sourceConnection, mapping);

        String insertQuery = populateInsertQuery(mapping);
        PreparedStatement insertStatement = targetConnection.prepareStatement(insertQuery);
        targetConnection.setAutoCommit(false);
        try {
            int currentStep = 1;
            while (rs.next()) {
                for (int i = 1; i <= columnMapping.size(); i++) {
                    insertStatement.setObject(i, rs.getObject(i));
                }
                insertStatement.addBatch();
                if (++currentStep > DEFAULT_BATCH_SIZE) {
                    insertStatement.executeBatch();
                    targetConnection.commit();
                    currentStep = 1;
                }
            }
            if (currentStep != 1) {
                insertStatement.executeBatch();
                targetConnection.commit();
            }
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
            targetConnection.rollback();
        } finally {
            insertStatement.close();
            rs.close();
        }
    }
}

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 {//www  . ja  v a 2 s.co  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 insertJsonResponse(int curConsId, TreeMap<Integer, String> input) throws SQLException {
    try {//from   w ww  . j a v a  2s . 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:module.entities.NameFinder.DB.java

public static void insertDemocracitConsultationMinister(TreeMap<Integer, String> consultationCountersign,
        TreeMap<Integer, String> consultationCounterrole) throws SQLException {
    try {//  w  w  w .j av  a 2s  .c om
        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.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);//from   w  w w.j a va2 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:com.streamsets.pipeline.lib.jdbc.MultiRowInsertMap.java

public void executeStatements() throws SQLException {
    for (PreparedStatement statement : cache.values()) {
        statement.executeBatch();
        statement.close();//from   w  w w . j  a  va2 s .co m
    }
}

From source file:org.accada.epcis.repository.capture.CaptureOperationsSession.java

public void commit() throws SQLException {
    for (PreparedStatement ps : batchInserts.values()) {
        ps.executeBatch();
    }//  ww  w .jav  a 2  s.  com
    connection.commit();
}

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

@Override
protected long finishUpdate(PreparedStatement insert) throws SQLException {
    long rowsUpdated = rowsUpdated(insert.executeBatch());
    counter.set(new AtomicInteger());
    return rowsUpdated;
}