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:connectivity.connection.java

public void sortLikes() throws SQLException, ParseException {
    PreparedStatement ps = con.prepareStatement("Select tip_id,likes_content from tips; ");

    ResultSet rs = ps.executeQuery();
    ArrayList likes = new ArrayList();
    while (rs.next()) {
        String[] arr = new String[2];
        arr[0] = rs.getString("tip_id");
        arr[1] = rs.getString("likes_content");
        likes.add(arr);/*from   www.  j a  v a  2  s.c  o  m*/
    }
    //System.out.println(likes);
    for (Object like : likes) {
        try {
            String[] arr = (String[]) like;
            JSONObject json = (JSONObject) new JSONParser().parse(arr[1]);
            //System.out.print(json.get("groups").toString());
            JSONArray groups = (JSONArray) new JSONParser().parse((json.get("groups").toString()));
            //Object [] a=(Object[]) user.get(0);
            JSONObject groups0 = (JSONObject) new JSONParser().parse((groups.get(0).toString()));
            JSONArray items = (JSONArray) new JSONParser().parse((groups0.get("items").toString()));
            for (Object item : items) {
                String ret = addUser((JSONObject) item);
                ps = con.prepareStatement("INSERT INTO `user_likes_tips` VALUES (?, ?);");
                ps.setString(1, ret);
                ps.setString(2, arr[0]);
                ps.addBatch();
            }
            ps.executeBatch();
            //System.out.print('a');
        } catch (Exception e) {
            System.out.println("exception e=" + e);
        }
    }
}

From source file:org.openbel.framework.core.kam.JdbcKAMLoaderImpl.java

/**
 * {@inheritDoc}/*from  w  ww. j a  v a 2s.  c  o  m*/
 */
@Override
public void loadAnnotationValues(AnnotationValueTable avt) throws SQLException {
    PreparedStatement aps = getPreparedStatement(ANNOTATION_SQL);
    Set<Entry<Integer, TableAnnotationValue>> annotationEntries = avt.getIndexValue().entrySet();
    for (Entry<Integer, TableAnnotationValue> annotationEntry : annotationEntries) {
        aps.setInt(1, (annotationEntry.getKey() + 1));

        TableAnnotationValue tableValue = annotationEntry.getValue();
        String value = tableValue.getAnnotationValue();

        int oid;
        Integer objectId = valueIndexMap.get(value);
        if (objectId != null) {
            oid = objectId;
        } else {
            oid = saveObject(1, value);
            valueIndexMap.put(value, oid);
        }

        aps.setInt(2, oid);
        aps.setInt(3, (tableValue.getAnnotationDefinitionId() + 1));
        aps.addBatch();
    }

    aps.executeBatch();
}

From source file:org.wso2.carbon.policy.mgt.core.dao.impl.MonitoringDAOImpl.java

@Override
public void addComplianceDetails(Map<Integer, Integer> devicePolicyMap) throws MonitoringDAOException {
    Connection conn;//from ww  w  .  java 2 s  .c  o m
    PreparedStatement stmt = null;
    ResultSet generatedKeys = null;
    Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    if (log.isDebugEnabled()) {
        log.debug("Adding the compliance details for devices and policies");
        for (Map.Entry<Integer, Integer> map : devicePolicyMap.entrySet()) {
            log.debug(map.getKey() + " -- " + map.getValue());
        }
    }
    try {
        conn = this.getConnection();
        String query = "INSERT INTO DM_POLICY_COMPLIANCE_STATUS (DEVICE_ID, POLICY_ID, STATUS, ATTEMPTS, "
                + "LAST_REQUESTED_TIME, TENANT_ID) VALUES (?, ?, ?,?, ?, ?) ";
        stmt = conn.prepareStatement(query);
        for (Map.Entry<Integer, Integer> map : devicePolicyMap.entrySet()) {
            stmt.setInt(1, map.getKey());
            stmt.setInt(2, map.getValue());
            stmt.setInt(3, 1);
            stmt.setInt(4, 1);
            stmt.setTimestamp(5, currentTimestamp);
            stmt.setInt(6, tenantId);
            stmt.addBatch();
        }
        stmt.executeBatch();
    } catch (SQLException e) {
        throw new MonitoringDAOException("Error occurred while adding the none compliance to the database.", e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
    }
}

From source file:org.wso2.carbon.apimgt.migration.client.MigrateFrom110to200.java

private void updateAuthzUserName() throws SQLException {
    log.info("Updating Authz UserName for API Manager started");
    Connection connection = null;
    PreparedStatement selectStatement = null;
    ResultSet resultSet = null;//from   w  ww . j  a  v a 2  s .  c o  m

    ArrayList<AccessTokenInfo> updateValues = new ArrayList<>();
    try {
        String selectQuery = "SELECT DISTINCT AUTHZ_USER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE AUTHZ_USER LIKE '%@%'";

        connection = APIMgtDBUtil.getConnection();
        selectStatement = connection.prepareStatement(selectQuery);
        resultSet = selectStatement.executeQuery();

        while (resultSet.next()) {
            String authzUser = resultSet.getString("AUTHZ_USER");

            String usernameWithoutDomain = MultitenantUtils.getTenantAwareUsername(authzUser);

            AccessTokenInfo accessTokenInfo = new AccessTokenInfo(usernameWithoutDomain, authzUser);
            updateValues.add(accessTokenInfo);
        }

    } finally {
        APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
    }

    if (!updateValues.isEmpty()) { // If user names that need to be updated exist
        PreparedStatement updateStatement = null;

        try {
            connection = APIMgtDBUtil.getConnection();
            connection.setAutoCommit(false);

            updateStatement = connection.prepareStatement(
                    "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET AUTHZ_USER = ?" + " WHERE AUTHZ_USER = ?");

            for (AccessTokenInfo accessTokenInfo : updateValues) {
                updateStatement.setString(1, accessTokenInfo.usernameWithoutDomain);
                updateStatement.setString(2, accessTokenInfo.authzUser);
                updateStatement.addBatch();
            }
            updateStatement.executeBatch();

            connection.commit();
        } finally {
            APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
        }
    }
    log.info("Updating Authz UserName for API Manager completed");
}

From source file:org.wso2.carbon.cluster.coordinator.rdbms.RDBMSCommunicationBusContextImpl.java

@Override
public void storeMembershipEvent(String changedMember, String groupId, List<String> clusterNodes,
        int membershipEventType) throws ClusterCoordinationException {
    Connection connection = null;
    PreparedStatement storeMembershipEventPreparedStatement = null;
    String task = "Storing membership event: " + membershipEventType + " for member: " + changedMember
            + " in group " + groupId;
    try {//  ww w .  ja  v  a2s  .  c o  m
        connection = getConnection();
        storeMembershipEventPreparedStatement = connection
                .prepareStatement(RDBMSConstants.PS_INSERT_MEMBERSHIP_EVENT);
        for (String clusterNode : clusterNodes) {
            storeMembershipEventPreparedStatement.setString(1, clusterNode);
            storeMembershipEventPreparedStatement.setString(2, groupId);
            storeMembershipEventPreparedStatement.setInt(3, membershipEventType);
            storeMembershipEventPreparedStatement.setString(4, changedMember);
            storeMembershipEventPreparedStatement.addBatch();
        }
        storeMembershipEventPreparedStatement.executeBatch();
        connection.commit();
    } catch (SQLException e) {
        rollback(connection, task);
        throw new ClusterCoordinationException("Error storing membership change: " + membershipEventType
                + " for member: " + changedMember + " in group " + groupId, e);
    } finally {
        close(storeMembershipEventPreparedStatement, task);
        close(connection, task);
    }
}

From source file:org.wso2.carbon.policy.mgt.core.dao.impl.MonitoringDAOImpl.java

@Override
public void addComplianceDetails(List<PolicyDeviceWrapper> policyDeviceWrapper) throws MonitoringDAOException {
    Connection conn;/*from   www .j  av  a  2 s .  co m*/
    PreparedStatement stmt = null;
    ResultSet generatedKeys = null;
    Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    if (log.isDebugEnabled()) {
        for (PolicyDeviceWrapper wrapper : policyDeviceWrapper) {
            log.debug("Policy Id : " + wrapper.getPolicyId() + " - " + " Device Id : " + wrapper.getDeviceId());
        }
    }
    try {
        conn = this.getConnection();
        String query = "INSERT INTO DM_POLICY_COMPLIANCE_STATUS (DEVICE_ID, POLICY_ID, STATUS, ATTEMPTS, "
                + "LAST_REQUESTED_TIME, TENANT_ID, ENROLMENT_ID) VALUES (?, ?, ?, ?, ?, ?, ?) ";
        stmt = conn.prepareStatement(query);
        for (PolicyDeviceWrapper wrapper : policyDeviceWrapper) {
            stmt.setInt(1, wrapper.getDeviceId());
            stmt.setInt(2, wrapper.getPolicyId());
            stmt.setInt(3, 1);
            stmt.setInt(4, 1);
            stmt.setTimestamp(5, currentTimestamp);
            stmt.setInt(6, tenantId);
            stmt.setInt(7, wrapper.getEnrolmentId());
            stmt.addBatch();
        }
        stmt.executeBatch();
    } catch (SQLException e) {
        throw new MonitoringDAOException("Error occurred while adding the none compliance to the database.", e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
    }
}

From source file:org.rhq.enterprise.server.measurement.MeasurementDataManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void addTraitData(Set<MeasurementDataTrait> data) {
    if ((data == null) || (data.isEmpty())) {
        return;/*www.j a v a 2s  .c om*/
    }

    Connection conn = null;
    PreparedStatement ps = null;
    try {
        conn = rhqDs.getConnection();
        ps = conn.prepareStatement(TRAIT_INSERT_STATEMENT);

        for (MeasurementDataTrait aData : data) {
            // time_stamp, schedule_id, value, schedule_id, schedule_id, value, value, value, value
            ps.setLong(1, aData.getTimestamp());
            ps.setInt(2, aData.getScheduleId());
            ps.setString(3, aData.getValue());
            ps.setInt(4, aData.getScheduleId());
            ps.setInt(5, aData.getScheduleId());
            ps.setString(6, aData.getValue());
            ps.setString(7, aData.getValue());
            ps.setString(8, aData.getValue());
            ps.setString(9, aData.getValue());
            ps.addBatch();
        }

        int[] res = ps.executeBatch();
        if (res.length != data.size()) {
            throw new MeasurementStorageException("Failure to store measurement trait data.");
            // It is expected that some of these batch updates didn't update anything as the previous value was the same
        }

        notifyAlertConditionCacheManager("mergeMeasurementReport",
                data.toArray(new MeasurementData[data.size()]));
    } catch (SQLException e) {
        log.warn("Failure saving measurement trait data:\n" + ThrowableUtil.getAllMessages(e));
    } catch (Exception e) {
        log.error("Error persisting trait data", e);
    } finally {
        JDBCUtil.safeClose(conn, ps, null);
    }
}

From source file:egovframework.rte.bat.core.item.database.EgovJdbcBatchItemWriter.java

/**
 * DB Write   ? setValues //from  w  ww .j  ava 2  s .c  o m
 * setValues(item, ps, params, sqlTypes, methodMap) : 
 * setValues(item, ps) :  VO
 */
@SuppressWarnings("unchecked")
public void write(final List<? extends T> items) throws Exception {

    if (!items.isEmpty()) {

        if (logger.isDebugEnabled()) {
            logger.debug("Executing batch with " + items.size() + " items.");
        }

        int[] updateCounts = null;

        updateCounts = (int[]) simpleJdbcTemplate.getJdbcOperations().execute(sql,
                new PreparedStatementCallback() {
                    public Object doInPreparedStatement(PreparedStatement ps)
                            throws SQLException, DataAccessException {
                        // Parameters   item, ps, params, sqlTypes,methodMap  ?  setValues call
                        //  item, ps  ?  setValues call
                        if (usingParameters) {

                            String[] sqlTypes = reflector.getSqlTypeArray(params, items.get(0));
                            try {
                                reflector.generateGetterMethodMap(params, items.get(0));
                            } catch (Exception e) {
                                // generateGetterMethodMap ?  ? 
                                logger.error(e);
                            }
                            Map<String, Method> methodMap = reflector.getMethodMap();

                            for (T item : items) {

                                itemPreparedStatementSetter.setValues(item, ps, params, sqlTypes, methodMap);
                                ps.addBatch();
                            }
                        } else {
                            for (T item : items) {
                                itemPreparedStatementSetter.setValues(item, ps);
                                ps.addBatch();
                            }
                        }
                        return ps.executeBatch();

                    }
                });

        if (assertUpdates) {

            for (int i = 0; i < updateCounts.length; i++) {
                int value = updateCounts[i];
                if (value == 0) {
                    throw new EmptyResultDataAccessException("Item " + i + " of " + updateCounts.length
                            + " did not update any rows: [" + items.get(i) + "]", 1);
                }
            }

        }
    }

}

From source file:edu.umd.cs.submitServer.servlets.LogEclipseLaunchEvent.java

/**
 * The doPost method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to
 * post.//  w w  w .  jav a 2s  .  c  om
 *
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = null;
    BufferedReader reader = null;
    try {
        MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);

        long clientTime = multipartRequest.getLongParameter("clientTime");
        long serverTime = System.currentTimeMillis();
        // Compute the "skew" between client and server in minutes.
        // This implicitly throw out things that are < 1 min so we lose the
        // regular
        // lagtime it takes to upload the submission and post the launch
        // events.
        int skew = (int) ((serverTime - clientTime) / 1000 / 60);

        StudentRegistration registration = (StudentRegistration) request.getAttribute("studentRegistration");
        Project project = (Project) request.getAttribute("project");

        FileItem fileItem = multipartRequest.getFileItem();
        reader = new BufferedReader(new InputStreamReader(fileItem.getInputStream()));
        String prevLine = null;
        conn = getConnection();
        PreparedStatement stmt = EclipseLaunchEvent.makeInsertStatement(conn);
        int count = 0;
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;
            if (line.equals(prevLine))
                continue;
            prevLine = line;
            // eclipseLaunchEvent date timestamp projectName event
            String tokens[] = line.split("\t");
            String timestampStr = tokens[1];
            String md5sum = tokens[2];
            String projectName = tokens[3];
            String event = tokens[4];

            getSubmitServerServletLog().debug(timestampStr + "\t" + md5sum + "\t" + projectName + "\t" + event);

            EclipseLaunchEvent eclipseLaunchEvent = new EclipseLaunchEvent();
            eclipseLaunchEvent.setStudentRegistrationPK(registration.getStudentRegistrationPK());
            eclipseLaunchEvent.setProjectNumber(projectName);
            eclipseLaunchEvent.setProjectPK(project.getProjectPK());
            eclipseLaunchEvent.setEvent(event);
            long timestamp = Long.valueOf(timestampStr);
            eclipseLaunchEvent.setTimestamp(new Timestamp(timestamp));
            eclipseLaunchEvent.setMd5sum(md5sum);
            eclipseLaunchEvent.setSkew(skew);
            eclipseLaunchEvent.fillInInsertStatement(stmt);
            stmt.addBatch();
            count++;
        }
        if (count > 0) {
            stmt.executeBatch();
            StudentSubmitStatus status = StudentSubmitStatus.lookupByStudentRegistrationPKAndProjectPK(
                    registration.getStudentRegistrationPK(), project.getProjectPK(), conn);
            if (status != null) {
                int totalEclipseLaunchEvents = EclipseLaunchEvent
                        .countEclipseLaunchEventsByProjectPKAndStudentRegistration(

                                project, registration, conn);
                status.setNumberRuns(totalEclipseLaunchEvents);
                status.update(conn);
            }
        }

    } catch (InvalidRequiredParameterException e) {
        ServletExceptionFilter.logErrorAndSendServerError(conn, ServerError.Kind.BAD_PARAMETERS, request, null,
                "LogEclipseLaunchEvent missing required parameter", "", e);
    } catch (SQLException e) {
        ServletExceptionFilter.logErrorAndSendServerError(conn, ServerError.Kind.EXCEPTION, request, null,
                "LogEclipseLaunchEvent missing required parameter", "", e);
    } finally {
        releaseConnection(conn);
        if (reader != null)
            reader.close();
    }
}

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

@Override
public Boolean ucitajPrognozeUBazu(ArrayList<Prognoza> prognoze) throws SQLException {

    Connection conn = null;//from  www . j  a  v a 2  s. c o  m
    Boolean status = false;

    try {
        conn = getConnection();
        conn.setAutoCommit(false);

        Statement s = conn.createStatement();
        ResultSet rs = s.executeQuery("SELECT AUTO_INCREMENT " + "FROM  INFORMATION_SCHEMA.TABLES "
                + "WHERE TABLE_SCHEMA = 'weather_forecasting' " + "AND   TABLE_NAME   = 'historija_prognoze';");

        int zadnjiId = -1;

        rs.next();
        zadnjiId = rs.getInt("AUTO_INCREMENT");

        int idGrada = -1;

        PreparedStatement pstmt = conn.prepareStatement(
                "INSERT INTO historija_prognoze (id, vrijeme, temp, pritisak, brzina_vjetra, vlaznost_zraka, datum) "
                        + "VALUES(?, ?,?,?,?,?,?)");

        PreparedStatement pstmt3 = conn
                .prepareStatement("INSERT INTO gradovi_prognoze (prognoza_id, grad_id) " + "VALUES(?,?)");

        for (Prognoza x : prognoze) {

            pstmt.clearParameters();
            pstmt.setInt(1, zadnjiId);
            pstmt.setString(2, x.getVrijeme());
            pstmt.setString(3, x.getTemperatura());
            pstmt.setString(4, x.getPritisakZraka());
            pstmt.setString(5, x.getBrzinaVjetra());
            pstmt.setString(6, x.getVlaznostZraka());
            pstmt.setDate(7, new java.sql.Date(x.getDatum().getTime()));
            pstmt.addBatch();

            idGrada = dajIdGradaPoImenu(x.getZaGrad().getImeGrada());

            pstmt3.clearParameters();
            pstmt3.setInt(1, zadnjiId);
            pstmt3.setInt(2, idGrada);

            pstmt3.addBatch();

            zadnjiId++;
        }

        pstmt.executeBatch();
        pstmt3.executeBatch();

        conn.commit();
        status = true;

    } catch (SQLException ex) {
        Logger.getLogger(MySqlDatabase.class.getName()).log(Level.SEVERE, null, ex);
        if (conn != null)
            conn.rollback();

    } finally {

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

    return status;
}