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:org.wso2.carbon.device.mgt.core.archival.dao.impl.ArchivalDAOImpl.java

@Override
public void copyOperationIDsForArchival(List<Integer> operationIds) throws ArchivalDAOException {
    PreparedStatement stmt = null;
    try {/*  w  w  w .  j  a  v a  2  s .  co  m*/
        Connection conn = ArchivalSourceDAOFactory.getConnection();
        String sql = "INSERT INTO DM_ARCHIVED_OPERATIONS(ID,CREATED_TIMESTAMP) VALUES (?,NOW())";
        stmt = conn.prepareStatement(sql);

        int count = 0;
        for (int i = 0; i < operationIds.size(); i++) {
            stmt.setInt(1, operationIds.get(i));
            stmt.addBatch();

            if (++count % this.batchSize == 0) {
                stmt.executeBatch();
            }
        }
        stmt.executeBatch();
        if (log.isDebugEnabled()) {
            log.debug(count + " Records copied to the temporary table.");
        }
    } catch (SQLException e) {
        throw new ArchivalDAOException("Error while copying operation Ids for archival", e);
    } finally {
        ArchivalDAOUtil.cleanupResources(stmt);
    }
}

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 ava  2 s  .  co m*/
        }

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

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

From source file:com.agiletec.aps.system.services.authorization.AuthorizationDAO.java

protected void addUserAuthorizations(String username, List<Authorization> authorizations, Connection conn) {
    PreparedStatement stat = null;
    try {/*from   w w w  .j av  a  2s.  com*/
        stat = conn.prepareStatement(ADD_AUTHORIZATION);
        for (int i = 0; i < authorizations.size(); i++) {
            Authorization auth = authorizations.get(i);
            if (null == auth)
                continue;
            stat.setString(1, username);
            if (null != auth.getGroup()) {
                stat.setString(2, auth.getGroup().getName());
            } else {
                stat.setNull(2, Types.VARCHAR);
            }
            if (null != auth.getRole()) {
                stat.setString(3, auth.getRole().getName());
            } else {
                stat.setNull(3, Types.VARCHAR);
            }
            stat.addBatch();
            stat.clearParameters();
        }
        stat.executeBatch();
    } catch (Throwable t) {
        _logger.error("Error detected while addind user authorizations", t);
        throw new RuntimeException("Error detected while addind user authorizations", t);
    } finally {
        this.closeDaoResources(null, stat);
    }
}

From source file:edu.harvard.i2b2.crc.dao.pdo.PdoQueryConceptDao.java

private void uploadTempTable(Statement tempStmt, String tempTable, List<String> patientNumList)
        throws SQLException {
    String createTempInputListTable = "create table " + tempTable + " ( char_param1 varchar(100) )";
    tempStmt.executeUpdate(createTempInputListTable);
    log.debug("created temp table" + tempTable);
    PreparedStatement preparedStmt = tempStmt.getConnection()
            .prepareStatement("insert into " + tempTable + " values (?)");
    // load to temp table
    // TempInputListInsert inputListInserter = new
    // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE);
    // inputListInserter.setBatchSize(100);
    int i = 0;//  w w  w  .  ja  v a2 s  .  com
    for (String singleValue : patientNumList) {
        preparedStmt.setString(1, singleValue);
        preparedStmt.addBatch();
        log.debug("adding batch [" + i + "] " + singleValue);
        i++;
        if (i % 100 == 0) {
            log.debug("batch insert [" + i + "]");
            preparedStmt.executeBatch();

        }
    }
    log.debug("batch insert [" + i + "]");
    preparedStmt.executeBatch();
}

From source file:com.nabla.dc.server.xml.settings.XmlCompany.java

public boolean save(final Connection conn, final Map<String, Integer> companyIds, final SaveContext ctx)
        throws SQLException, DispatchException {
    Integer companyId = companyIds.get(getName());
    if (companyId != null) {
        if (ctx.getOption() == SqlInsertOptions.APPEND)
            return true;
        Database.executeUpdate(conn, "UPDATE company SET active=? WHERE id=?;", active, companyId);
        Database.executeUpdate(conn, "DELETE FROM financial_year WHERE company_id=?;", companyId);
        if (accounts != null) {
            if (log.isDebugEnabled())
                log.debug("deleting all accounts of company '" + getName() + "'");
            accounts.clear(conn, companyId);
        }//from   ww  w.  ja v  a2 s  .  co m
        if (asset_categories != null)
            asset_categories.clear(conn, companyId);
        if (users != null)
            users.clear(conn, companyId);
    } else {
        companyId = Database.addRecord(conn, "INSERT INTO company (name,uname,active) VALUES(?,?,?);",
                getName(), getName().toUpperCase(), active);
        if (companyId == null)
            throw new InternalErrorException(Util.formatInternalErrorDescription("failed to insert company"));
        companyIds.put(getName(), companyId);
    }
    final Integer financialYearId = Database.addRecord(conn,
            "INSERT INTO financial_year (company_id, name) VALUES(?,?);", companyId, financial_year);
    final PreparedStatement stmt = conn
            .prepareStatement("INSERT INTO period_end (financial_year_id,name,end_date) VALUES(?,?,?);");
    try {
        stmt.setInt(1, financialYearId);
        final Calendar dt = new GregorianCalendar();
        dt.setTime(start_date);
        final SimpleDateFormat financialYearFormat = new SimpleDateFormat("MMM yyyy");
        for (int m = 0; m < 12; ++m) {
            dt.set(GregorianCalendar.DAY_OF_MONTH, dt.getActualMaximum(GregorianCalendar.DAY_OF_MONTH));
            final Date end = new Date(dt.getTime().getTime());
            stmt.setString(2, financialYearFormat.format(end));
            stmt.setDate(3, end);
            stmt.addBatch();
            dt.add(GregorianCalendar.MONTH, 1);
        }
        if (!Database.isBatchCompleted(stmt.executeBatch()))
            throw new InternalErrorException(Util
                    .formatInternalErrorDescription("fail to insert periods for company '" + getName() + "'"));
    } finally {
        stmt.close();
    }
    if (accounts != null)
        accounts.save(conn, companyId);
    return (asset_categories == null || asset_categories.save(conn, companyId, ctx))
            && (users == null || users.save(conn, companyId, ctx));
}

From source file:com.spvp.dal.MySqlDatabase.java

@Override
public Boolean ucitajGradoveUBazu(ArrayList<Grad> gradovi) throws SQLException {

    Connection conn = null;//from   ww  w.j ava 2s. c  om
    Boolean status = false;

    try {
        conn = getConnection();

        PreparedStatement pstmt = conn.prepareStatement(
                "INSERT INTO gradovi (ime, longitude, latitude, veci_centar)" + "VALUES(?,?,?,?)");
        for (Grad x : gradovi) {

            pstmt.clearParameters();
            pstmt.setString(1, x.getImeGrada());
            pstmt.setDouble(2, x.getLongitude());
            pstmt.setDouble(3, x.getLatitude());
            pstmt.setBoolean(4, x.getVeciCentar());

            pstmt.addBatch();
        }

        pstmt.executeBatch();
        status = true;

    } catch (SQLException ex) {
        Logger.getLogger(MySqlDatabase.class.getName()).log(Level.SEVERE, null, ex);

    } finally {

        if (conn != null)
            conn.close();
    }

    return status;
}

From source file:org.callimachusproject.behaviours.SqlDatasourceSupport.java

private void loadIntoTable(TupleQueryResult rows, String tablename, Connection conn)
        throws QueryEvaluationException, SQLException {
    List<String> columns = rows.getBindingNames();
    Map<String, Integer> columnTypes = getColumnTypes(tablename, conn);
    PreparedStatement insert = prepareInsert(columns, tablename, conn);
    try {//from w ww  . ja  v  a2  s. co  m
        for (int count = 1; rows.hasNext(); count++) {
            BindingSet row = rows.next();
            for (int i = 0, n = columns.size(); i < n; i++) {
                String column = columns.get(i);
                Integer type = columnTypes.get(column);
                Value value = row.getValue(column);
                int col = i + 1;
                setValue(insert, col, value, type);
            }
            insert.addBatch();
            if (count % BATCH_SIZE == 0) {
                insert.executeBatch();
            }
        }
        insert.executeBatch();
    } finally {
        insert.close();
    }
}

From source file:org.plista.kornakapi.core.storage.MySqlStorage.java

@Override
public void batchSetPreferences(Iterator<Preference> preferences, int batchSize) throws IOException {
    Connection conn = null;/*from   w  ww . jav a  2  s .co m*/
    PreparedStatement stmt = null;

    try {
        conn = dataSource.getConnection();
        stmt = conn.prepareStatement(IMPORT_QUERY);

        int recordsQueued = 0;

        while (preferences.hasNext()) {
            Preference preference = preferences.next();
            stmt.setLong(1, preference.getUserID());
            stmt.setLong(2, preference.getItemID());
            stmt.setFloat(3, preference.getValue());
            stmt.addBatch();

            if (++recordsQueued % batchSize == 0) {
                stmt.executeBatch();
                log.info("imported {} records in batch", recordsQueued);
            }
        }

        if (recordsQueued % batchSize != 0) {
            stmt.executeBatch();
            log.info("imported {} records in batch. done.", recordsQueued);
        }

    } catch (SQLException e) {
        throw new IOException(e);
    } finally {
        IOUtils.quietClose(stmt);
        IOUtils.quietClose(conn);
    }
}

From source file:org.wso2.carbon.analytics.datasource.rdbms.RDBMSAnalyticsRecordStore.java

private void mergeRecordsSimilar(Connection conn, List<Record> records, String tableName, String query)
        throws SQLException, AnalyticsException {
    PreparedStatement stmt = null;
    try {/* ww  w .  j  a va 2 s  .co  m*/
        stmt = conn.prepareStatement(query);
        for (Record record : records) {
            this.populateStatementForAdd(stmt, record);
            stmt.addBatch();
        }
        stmt.executeBatch();
        conn.commit();
    } catch (SQLException e) {
        RDBMSUtils.rollbackConnection(conn);
        if (!this.tableExists(conn, tableName)) {
            throw new AnalyticsTableNotAvailableException(tableName);
        } else {
            throw e;
        }
    } finally {
        RDBMSUtils.cleanupConnection(null, stmt, null);
    }
}

From source file:org.plista.kornakapi.core.storage.MySqlStorage.java

@Override
public Iterable<String> batchAddCandidates(Iterator<Candidate> candidates, int batchSize) throws IOException {

    Set<String> modifiedLabels = Sets.newHashSet();

    Connection conn = null;//from  w ww .  ja  va2 s.  c  om
    PreparedStatement stmt = null;

    try {
        conn = dataSource.getConnection();
        stmt = conn.prepareStatement(INSERT_CANDIDATE_QUERY);

        int recordsQueued = 0;

        while (candidates.hasNext()) {

            Candidate candidate = candidates.next();

            modifiedLabels.add(candidate.getLabel());

            stmt.setString(1, candidate.getLabel());
            stmt.setLong(2, candidate.getItemID());
            stmt.addBatch();

            if (++recordsQueued % batchSize == 0) {
                stmt.executeBatch();
                log.info("imported {} candidates in batch", recordsQueued);
            }
        }

        if (recordsQueued % batchSize != 0) {
            stmt.executeBatch();
            log.info("imported {} candidates in batch. done.", recordsQueued);
        }

    } catch (SQLException e) {
        throw new IOException(e);
    } finally {
        IOUtils.quietClose(stmt);
        IOUtils.quietClose(conn);
    }

    return modifiedLabels;
}