List of usage examples for java.sql PreparedStatement executeBatch
int[] executeBatch() throws SQLException;
From source file:org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl.java
@Override public void markPoliciesAsUpdated(List<Integer> policyIds) throws PolicyManagerDAOException { Connection conn;/* w ww . ja v a 2 s . c o m*/ PreparedStatement stmt = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { conn = this.getConnection(); String query = "UPDATE DM_POLICY SET UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(query); for (int policyId : policyIds) { stmt.setInt(1, 0); stmt.setInt(2, policyId); stmt.setInt(3, tenantId); stmt.addBatch(); } stmt.executeBatch(); } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while updating all the updated in database", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, null); } }
From source file:fr.aliacom.obm.common.contact.ContactDaoJdbcImpl.java
private PreparedStatement insertPhones(Connection con, EntityId entityId, Map<String, Phone> phones) throws SQLException { PreparedStatement ps; ps = con.prepareStatement(/*from www.j a va2 s . c o m*/ "INSERT INTO Phone (phone_entity_id, phone_label, phone_number) " + "VALUES (?, ?, ?)"); for (Entry<String, Phone> entry : phones.entrySet()) { ps.setInt(1, entityId.getId()); ps.setString(2, entry.getKey()); ps.setString(3, entry.getValue().getNumber()); ps.addBatch(); } ps.executeBatch(); return ps; }
From source file:fr.aliacom.obm.common.contact.ContactDaoJdbcImpl.java
private PreparedStatement insertEmails(Connection con, EntityId entityId, Map<String, EmailAddress> emails) throws SQLException { PreparedStatement ps; ps = con.prepareStatement(//ww w .j a va2 s.co m "INSERT INTO Email (email_entity_id, email_label, email_address) " + "VALUES (?, ?, ?)"); for (Entry<String, EmailAddress> entry : emails.entrySet()) { ps.setInt(1, entityId.getId()); ps.setString(2, entry.getKey()); ps.setString(3, entry.getValue().get()); ps.addBatch(); } ps.executeBatch(); return ps; }
From source file:org.rhq.enterprise.server.measurement.CallTimeDataManagerBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void insertCallTimeDataKeys(Set<CallTimeData> callTimeDataSet) { int[] results; String insertKeySql;//from w w w . j a va 2 s. c om PreparedStatement ps = null; Connection conn = null; try { conn = rhqDs.getConnection(); DatabaseType dbType = DatabaseTypeFactory.getDatabaseType(conn); if (dbType instanceof Postgresql83DatabaseType) { Statement st = null; try { // Take advantage of async commit here st = conn.createStatement(); st.execute("SET synchronous_commit = off"); } finally { JDBCUtil.safeClose(st); } } if (dbType instanceof PostgresqlDatabaseType || dbType instanceof OracleDatabaseType || dbType instanceof H2DatabaseType) { String keyNextvalSql = JDBCUtil.getNextValSql(conn, "RHQ_calltime_data_key"); insertKeySql = String.format(CALLTIME_KEY_INSERT_STATEMENT, keyNextvalSql); } else if (dbType instanceof SQLServerDatabaseType) { insertKeySql = CALLTIME_KEY_INSERT_STATEMENT_AUTOINC; } else { throw new IllegalArgumentException("Unknown database type, can't continue: " + dbType); } ps = conn.prepareStatement(insertKeySql); for (CallTimeData callTimeData : callTimeDataSet) { ps.setInt(1, callTimeData.getScheduleId()); ps.setInt(3, callTimeData.getScheduleId()); Set<String> callDestinations = callTimeData.getValues().keySet(); for (String callDestination : callDestinations) { ps.setString(2, callDestination); ps.setString(4, callDestination); ps.addBatch(); } } results = ps.executeBatch(); int insertedRowCount = 0; for (int i = 0; i < results.length; i++) { if (((results[i] < 0) || (results[i] > 1)) && (results[i] != -2)) // oracle returns -2 because it can't count updated rows { throw new MeasurementStorageException("Failed to insert call-time data key rows - result [" + results[i] + "] for batch command [" + i + "] is less than 0 or greater than 1."); } insertedRowCount += results[i] == -2 ? 1 : results[i]; // If Oracle returns -2, just count 1 row } log.debug( "Inserted new call-time data key rows for " + ((insertedRowCount >= 0) ? insertedRowCount : "?") + " out of " + results.length + " reported key-value pairs."); } catch (SQLException e) { logSQLException("Failed to persist call-time data keys", e); } catch (Throwable t) { log.error("Failed to persist call-time data keys", t); } finally { JDBCUtil.safeClose(conn, ps, null); } }
From source file:org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl.java
@Override public void activatePolicies(List<Integer> policyIds) throws PolicyManagerDAOException { Connection conn;//from w w w. j a v a 2s . c om PreparedStatement stmt = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { conn = this.getConnection(); String query = "UPDATE DM_POLICY SET UPDATED = ?, ACTIVE = ? WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(query); for (int policyId : policyIds) { stmt.setInt(1, 1); stmt.setInt(2, 1); stmt.setInt(3, policyId); stmt.setInt(4, tenantId); stmt.addBatch(); } stmt.executeBatch(); } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while updating all the updated in database", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, null); } }
From source file:com.mtgi.analytics.JdbcBehaviorEventPersisterImpl.java
public void persist(final Queue<BehaviorEvent> events) { getJdbcTemplate().execute(new ConnectionCallback() { public Object doInConnection(Connection con) throws SQLException, DataAccessException { //if this connection is behavior tracking, suspend tracking. //we don't generate more events while persisting. BehaviorTrackingConnectionProxy bt = null; for (Connection c = con; bt == null && c instanceof ConnectionProxy; c = ((ConnectionProxy) c).getTargetConnection()) { if (c instanceof BehaviorTrackingConnectionProxy) { bt = (BehaviorTrackingConnectionProxy) c; bt.suspendTracking(); }// w ww .j av a 2 s. co m } try { boolean doBatch = supportsBatchUpdates(con); EventDataElementSerializer dataSerializer = new EventDataElementSerializer(xmlFactory); PreparedStatement[] idStmt = { null }; PreparedStatement insert = con.prepareStatement(insertSql); try { //keep track of statements added to the batch so that we can time our //flushes. int batchCount = 0; for (BehaviorEvent next : events) { //event may already have an ID assigned if any //of its child events has been persisted. assignIds(next, con, idStmt); //populate identifying information for the event into the insert statement. insert.setLong(1, (Long) next.getId()); BehaviorEvent parent = next.getParent(); nullSafeSet(insert, 2, parent == null ? null : parent.getId(), Types.BIGINT); insert.setString(3, next.getApplication()); insert.setString(4, next.getType()); insert.setString(5, next.getName()); insert.setTimestamp(6, new java.sql.Timestamp(next.getStart().getTime())); insert.setLong(7, next.getDurationNs()); //set optional context information on the event. nullSafeSet(insert, 8, next.getUserId(), Types.VARCHAR); nullSafeSet(insert, 9, next.getSessionId(), Types.VARCHAR); nullSafeSet(insert, 10, next.getError(), Types.VARCHAR); //convert event data to XML String data = dataSerializer.serialize(next.getData(), true); nullSafeSet(insert, 11, data, Types.VARCHAR); if (doBatch) { insert.addBatch(); if (++batchCount >= batchSize) { insert.executeBatch(); batchCount = 0; } } else { insert.executeUpdate(); } } //flush any lingering batch inserts through to the server. if (batchCount > 0) insert.executeBatch(); } finally { closeStatement(insert); closeStatement(idStmt[0]); } return null; } finally { if (bt != null) bt.resumeTracking(); } } }); }
From source file:org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl.java
@Override public Policy addPolicyToDevice(List<Device> devices, Policy policy) throws PolicyManagerDAOException { Connection conn;/*from w w w. j a v a2s. c om*/ PreparedStatement stmt = null; try { conn = this.getConnection(); String query = "INSERT INTO DM_DEVICE_POLICY (DEVICE_ID, POLICY_ID, ENROLMENT_ID, DEVICE) VALUES (?, ?, " + "?, ?)"; stmt = conn.prepareStatement(query); for (Device device : devices) { stmt.setInt(1, device.getId()); stmt.setInt(2, policy.getId()); stmt.setInt(3, device.getEnrolmentInfo().getId()); stmt.setBytes(4, PolicyManagerUtil.getBytes(device)); stmt.addBatch(); } stmt.executeBatch(); } catch (SQLException e) { throw new PolicyManagerDAOException( "Error occurred while adding the device ids with policy to " + "database", e); } catch (IOException e) { throw new PolicyManagerDAOException("Error occurred while getting the byte array from device.", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, null); } return policy; }
From source file:org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl.java
@Override public boolean updatePolicyPriorities(List<Policy> policies) throws PolicyManagerDAOException { Connection conn;// w w w. j a v a2s . co m PreparedStatement stmt = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { conn = this.getConnection(); String query = "UPDATE DM_POLICY SET PRIORITY = ?, UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(query); for (Policy policy : policies) { stmt.setInt(1, policy.getPriorityId()); stmt.setInt(2, 1); stmt.setInt(3, policy.getId()); stmt.setInt(4, tenantId); stmt.addBatch(); } stmt.executeBatch(); } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while updating policy priorities in database", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, null); } return true; }
From source file:com.flexive.ejb.beans.BriefcaseEngineBean.java
/** * {@inheritDoc}/*from w w w . j a v a 2 s . c om*/ */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void addItems(long id, Collection<FxPK> contents) throws FxApplicationException { Connection con = null; PreparedStatement stmt = null; final Briefcase br = load(id); checkEditBriefcase(br); try { con = Database.getDbConnection(); // keep lookup table of existing items to avoid adding an item twice final Set<Long> existingItems = new HashSet<Long>(); final long[] items = getItems(id); for (long item : items) { existingItems.add(item); } stmt = con.prepareStatement("SELECT MAX(pos) FROM " + TBL_BRIEFCASE_DATA + " WHERE briefcase_id=?"); stmt.setLong(1, id); final ResultSet rs = stmt.executeQuery(); int pos = rs.next() ? rs.getInt(1) : 0; stmt.close(); stmt = con.prepareStatement( "INSERT INTO " + TBL_BRIEFCASE_DATA + "(briefcase_id, id, pos, amount) VALUES (?, ?, ?, 1)"); stmt.setLong(1, id); for (FxPK pk : contents) { if (!existingItems.contains(pk.getId())) { stmt.setLong(2, pk.getId()); stmt.setLong(3, ++pos); stmt.addBatch(); existingItems.add(pk.getId()); } } stmt.executeBatch(); } catch (Exception e) { EJBUtils.rollback(ctx); throw new FxUpdateException(LOG, e, "ex.briefcase.addItems", br.getName(), e); } finally { closeObjects(BriefcaseEngineBean.class, con, stmt); } }
From source file:org.wso2.carbon.cluster.coordinator.rdbms.RDBMSCommunicationBusContextImpl.java
@Override public void insertRemovedNodeDetails(String removedMember, String groupId, List<String> clusterNodes, Map<String, Object> removedPropertiesMap) throws ClusterCoordinationException { Connection connection = null; PreparedStatement storeRemovedMembersPreparedStatement = null; String task = "Storing removed member: " + removedMember + " in group " + groupId; try {//from w w w . j ava2 s. c o m connection = getConnection(); storeRemovedMembersPreparedStatement = connection .prepareStatement(RDBMSConstants.PS_INSERT_REMOVED_MEMBER_DETAILS); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(removedPropertiesMap); objectOutputStream.flush(); byteArrayOutputStream.flush(); objectOutputStream.close(); byteArrayOutputStream.close(); byte[] propertiesMapAsBytes = byteArrayOutputStream.toByteArray(); // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(propertiesMapAsBytes); for (String clusterNode : clusterNodes) { storeRemovedMembersPreparedStatement.setString(1, clusterNode); storeRemovedMembersPreparedStatement.setString(2, groupId); storeRemovedMembersPreparedStatement.setString(3, removedMember); storeRemovedMembersPreparedStatement.setBinaryStream(4, new ByteArrayInputStream(propertiesMapAsBytes)); storeRemovedMembersPreparedStatement.addBatch(); } storeRemovedMembersPreparedStatement.executeBatch(); connection.commit(); } catch (SQLException e) { rollback(connection, task); throw new ClusterCoordinationException( "Error storing removed member: " + removedMember + " in group " + groupId, e); } catch (IOException e) { throw new ClusterCoordinationException("Error while inserting removed node data", e); } finally { close(storeRemovedMembersPreparedStatement, task); close(connection, task); } }