List of usage examples for java.sql PreparedStatement addBatch
void addBatch() throws SQLException;
PreparedStatement
object's batch of commands. From source file:org.plista.kornakapi.core.storage.MySqlStorage.java
@Override public Iterable<String> batchDeleteCandidates(Iterator<Candidate> candidates, int batchSize) throws IOException { Set<String> modifiedLabels = Sets.newHashSet(); Connection conn = null;/*from w ww. jav a 2 s . c om*/ PreparedStatement stmt = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement(REMOVE_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("deleted {} candidates in batch", recordsQueued); } } if (recordsQueued % batchSize != 0) { stmt.executeBatch(); log.info("deleted {} candidates in batch. done.", recordsQueued); } } catch (SQLException e) { throw new IOException(e); } finally { IOUtils.quietClose(stmt); IOUtils.quietClose(conn); } return modifiedLabels; }
From source file:org.accada.epcis.repository.capture.CaptureOperationsBackendSQL.java
/** * {@inheritDoc}//from ww w. ja v a2 s. c o m */ public void insertBusinessTransactionsForEvent(final CaptureOperationsSession session, final long eventId, final String eventType, final List<BusinessTransactionType> btts) throws SQLException { // preparing statement for insertion of associated EPCs List<Long> btIds = new ArrayList<Long>(); for (BusinessTransactionType btt : btts) { btIds.add(getOrInsertBizTransaction(session, btt.getValue(), btt.getType())); } String insert = "INSERT INTO event_" + eventType + "_bizTrans (event_id, bizTrans_id) VALUES (?, ?)"; if (LOG.isDebugEnabled()) { LOG.debug("INSERT: " + insert); } PreparedStatement ps = session.getBatchInsert(insert); // insert all BizTransactions into the BusinessTransaction-Table // and connect it with the "event_<event-name>_bizTrans"-Table for (long btId : btIds) { if (LOG.isDebugEnabled()) { LOG.debug(" insert param 1: " + eventId); LOG.debug(" insert param 2: " + btId); } ps.setLong(1, eventId); ps.setLong(2, btId); ps.addBatch(); } }
From source file:org.apache.gora.sql.store.SqlStore.java
@Override public void put(K key, T persistent) throws IOException { boolean hasDirty = false; try {/* ww w . j a v a 2 s. c om*/ // TODO: INSERT or UPDATE Schema schema = persistent.getSchema(); StateManager stateManager = persistent.getStateManager(); List<Field> fields = schema.getFields(); InsertUpdateStatement<K, T> insertStatement = InsertUpdateStatementFactory.createStatement(this, mapping, dbVendor); insertStatement.setObject(key, null, mapping.getPrimaryColumn()); for (int i = 0; i < fields.size(); i++) { Field field = fields.get(i); if (!stateManager.isDirty(persistent, i)) { continue; } hasDirty = true; Column column = mapping.getColumn(field.name()); insertStatement.setObject(persistent.get(i), field.schema(), column); } if (!hasDirty) { return; } // jdbc already should cache the ps PreparedStatement insert = insertStatement.toStatement(connection); insert.addBatch(); synchronized (writeCache) { writeCache.add(insert); /* * TODO set the magic number in the configuration */ int size = writeCache.size(); if (size >= 100) flush(); } } catch (Exception ex) { throw new IOException(ex); } }
From source file:org.wso2.carbon.policy.mgt.core.dao.impl.feature.AbstractFeatureDAO.java
@Override public List<ProfileFeature> updateProfileFeatures(List<ProfileFeature> features, int profileId) throws FeatureManagerDAOException { Connection conn;/*from w w w. ja v a 2s .co m*/ PreparedStatement stmt = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { conn = this.getConnection(); String query = "UPDATE DM_PROFILE_FEATURES SET CONTENT = ? WHERE PROFILE_ID = ? AND FEATURE_CODE = ? AND" + " TENANT_ID = ?"; stmt = conn.prepareStatement(query); for (ProfileFeature feature : features) { stmt.setBytes(1, PolicyManagerUtil.getBytes(feature.getContent())); stmt.setInt(2, profileId); stmt.setString(3, feature.getFeatureCode()); stmt.setInt(4, tenantId); stmt.addBatch(); //Not adding the logic to check the size of the stmt and execute if the size records added is over 1000 } stmt.executeBatch(); } catch (SQLException | IOException e) { throw new FeatureManagerDAOException("Error occurred while adding the feature list to the database.", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, null); } return features; }
From source file:com.spvp.dal.MySqlDatabase.java
@Override public Boolean ucitajGradoveUBazu(ArrayList<Grad> gradovi) throws SQLException { Connection conn = null;/*from w w w .j a v a2 s . co m*/ 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:com.yahoo.ycsb.db.PostgreSQLJsonbClient.java
@Override public Status insert(String tableName, String key, HashMap<String, ByteIterator> values) { try {//from www . jav a 2s .com StatementType type = new StatementType(StatementType.Type.INSERT, tableName, 1, "fields", getShardIndexByKey(key)); PreparedStatement insertStatement = cachedStatements.get(type); if (insertStatement == null) { insertStatement = createAndCacheInsertStatement(type, key); } String value = getJsonString(values); insertStatement.setString(1, key); insertStatement.setString(2, value); int result; if (batchSize > 0) { insertStatement.addBatch(); if (++numRowsInBatch % batchSize == 0) { int[] results = insertStatement.executeBatch(); for (int r : results) { if (r != 1) { return Status.ERROR; } } return Status.OK; } return Status.BATCHED_OK; } else { result = insertStatement.executeUpdate(); } if (result == 1) { return Status.OK; } return Status.UNEXPECTED_STATE; } catch (SQLException e) { System.err.println("Error in processing insert to table: " + tableName + e); return Status.ERROR; } }
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 {/*w ww . j a v a2 s . c o 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:com.ea.core.orm.handle.impl.HibernateSqlORMHandle.java
@Override protected Object execute(ORMParamsDTO dto) throws Exception { // TODO Auto-generated method stub Session session = this.getHibernateSessionFactory().getCurrentSession(); final ORMParamsDTO tmp = dto; session.doWork(new Work() { @SuppressWarnings("rawtypes") public void execute(Connection connection) throws SQLException { // connectionJDBC // closeconnection System.out.println("sql:" + tmp.getSqlid()); PreparedStatement ps = connection.prepareStatement(tmp.getSqlid()); if (tmp.getParam() != null) { Object data = tmp.getParam(); if (data instanceof Object[]) { Object[] array = (Object[]) data; int index = 1; for (Object obj : array) { setParam(ps, index++, obj); }//from w w w .j a v a 2 s .c o m ps.execute(); } else if (data instanceof Collection) { for (Object array : (Collection) data) { if (array instanceof Object[]) { int index = 1; for (Object obj : (Object[]) array) { setParam(ps, index++, obj); } ps.addBatch(); } else { throw new SQLException("SQL?Object[]???!"); } } ps.executeBatch(); } else { throw new SQLException( "SQL????Object[]???????CollectionObject[]!"); } } } }); return null; }
From source file:coral.data.DataServiceJbdcImpl.java
private long put(long id, String collection, Map<String, String> map) throws SQLException { if (map.size() > 0) { PreparedStatement prep = conn.prepareStatement("insert into datas values (?, ?, ?, ?);"); for (Map.Entry<String, String> e : map.entrySet()) { prep.setString(1, Long.toString(id)); prep.setString(2, collection); prep.setString(3, e.getKey()); String v = e.getValue(); prep.setString(4, v.substring(0, (v.length() > 1000) ? 1000 : v.length())); prep.addBatch(); }//from w ww. jav a 2 s . com conn.setAutoCommit(false); prep.executeBatch(); conn.setAutoCommit(true); } conn.commit(); return id; }
From source file:net.mybox.mybox.ServerClientConnection.java
private void sendServerFileList() { System.out.println("getting local file list for: " + localDir); Statement statement = null;/*from w w w.j a v a2s . co m*/ // refresh the database try { statement = connection.createStatement(); statement.setQueryTimeout(30); statement.executeUpdate( "create table if not exists archive (name text primary key, type char(1), lastupdate integer)"); } catch (Exception e) { System.out.println("SQLite error: " + e.getMessage()); } try { List<MyFile> files = Common.getFileListing(new File(localDir)); JSONArray jsonArray = new JSONArray(); PreparedStatement prep = connection.prepareStatement("insert or ignore into archive values(?,?,?);"); for (MyFile thisFile : files) { System.out.println(" " + thisFile.name); // TODO: do not insert directories that are already in the DB // compare against getFilesFromDB ? prep.setString(1, thisFile.name); prep.setString(2, thisFile.getTypeChar() + ""); prep.setLong(3, thisFile.modtime); prep.addBatch(); jsonArray.add(thisFile.serialize()); } prep.executeBatch(); connection.commit(); sendCommandToClient(Common.Signal.requestServerFileList_response); ByteStream.toStream(outStream, jsonArray.toJSONString()); System.out.println("local file list: " + jsonArray.size() + " files"); } catch (Exception e) { System.out.println("Error when getting local file list " + e.getMessage()); } }