List of usage examples for java.sql PreparedStatement addBatch
void addBatch() throws SQLException;
PreparedStatement
object's batch of commands. From source file:org.wso2.carbon.analytics.datasource.rdbms.RDBMSAnalyticsFileSystem.java
private void writeChunksInsertOrUpdate(String path, List<DataChunk> chunks) throws IOException { Connection conn = null;//from w w w . jav a 2s . c o m PreparedStatement stmt = null; try { conn = this.getConnection(false); stmt = conn.prepareStatement(this.getWriteDataChunkQuery()); for (DataChunk chunk : chunks) { this.populateStatementWithDataChunk(stmt, path, chunk); stmt.addBatch(); } stmt.executeBatch(); conn.commit(); } catch (SQLException e) { RDBMSUtils.rollbackConnection(conn); /* this is maybe because we are updating some data already in the file with a seek operation, * and the given write chunk query is not an insert or update, so lets insert sequentially * and check, if an error comes, a separate update statement will be executed and checked */ if (log.isDebugEnabled()) { log.debug("Chunk batch write failed: " + e.getMessage() + ", falling back to sequential insert/update.."); } RDBMSUtils.cleanupConnection(null, stmt, null); stmt = null; this.writeChunksSequentially(conn, path, chunks); } finally { RDBMSUtils.cleanupConnection(null, stmt, conn); } }
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 {// w w w .j av a 2 s.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:org.wso2.carbon.is.migration.dao.IdpMetaDataDAO.java
public void addIdpMetaData(List<IdpMetaData> idpMetaDataDAOs) throws ISMigrationException { String sql = "INSERT INTO IDP_METADATA(IDP_ID, NAME, VALUE, DISPLAY_NAME, TENANT_ID) values(?,?,?,?,?)"; PreparedStatement prepStmt = null; Connection connection = IdentityDatabaseUtil.getDBConnection(); try {/*from w w w. j av a2 s . c o m*/ String dbProductName = connection.getMetaData().getDatabaseProductName(); prepStmt = connection.prepareStatement(sql, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, SQLConstants.ID_COLUMN) }); for (IdpMetaData idpMetaData : idpMetaDataDAOs) { prepStmt.setInt(1, idpMetaData.getIdpId()); prepStmt.setString(2, idpMetaData.getName()); prepStmt.setString(3, idpMetaData.getValue()); prepStmt.setString(4, idpMetaData.getDisplayName()); prepStmt.setInt(5, idpMetaData.getTenantId()); prepStmt.addBatch(); } prepStmt.executeBatch(); connection.commit(); } catch (SQLException e) { throw new ISMigrationException("Error while inserting default resident idp property values.", e); } finally { IdentityDatabaseUtil.closeStatement(prepStmt); } }
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 w w . ja v a 2s .c o 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:connectivity.connection.java
private String addUser(JSONObject user) throws SQLException { //System.out.println(user.get("id")); PreparedStatement ps = con.prepareStatement("Select user_id from users where user_id=?"); ps.setString(1, user.get("id").toString()); ResultSet rs = ps.executeQuery(); if (rs.next()) { return user.get("id").toString(); } else {/*from ww w.j a va2 s . com*/ ps = con.prepareStatement( "INSERT INTO `users` (`user_id`, `firstname`, `gender`, `photo`) VALUES (?, ?, ?, ?);"); ps.setString(1, user.get("id").toString()); ps.setString(2, user.get("firstName").toString()); ps.setString(3, user.get("gender").toString()); ps.setString(4, gson.toJson(user.get("photo"))); ps.addBatch(); ps.executeBatch(); return user.get("id").toString(); } }
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 w w .j av a 2 s.c om 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.wso2.carbon.device.mgt.extensions.device.type.template.dao.PropertyBasedPluginDAOImpl.java
public boolean addDevice(Device device) throws DeviceTypeMgtPluginException { boolean status = false; Connection conn = null;/*from w w w . ja v a 2 s.c o m*/ PreparedStatement stmt = null; try { conn = deviceTypeDAOHandler.getConnection(); stmt = conn.prepareStatement( "INSERT INTO DM_DEVICE_PROPERTIES(DEVICE_TYPE_NAME, DEVICE_IDENTIFICATION, PROPERTY_NAME, " + "PROPERTY_VALUE, TENANT_ID) VALUES (?, ?, ?, ?, ?)"); for (String propertyKey : deviceProps) { stmt.setString(1, deviceType); stmt.setString(2, device.getDeviceIdentifier()); stmt.setString(3, propertyKey); stmt.setString(4, getPropertyValue(device.getProperties(), propertyKey)); stmt.setInt(5, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true)); stmt.addBatch(); } stmt.executeBatch(); status = true; } catch (SQLException e) { String msg = "Error occurred while adding the device '" + device.getDeviceIdentifier() + "' to the type " + deviceType + " db."; log.error(msg, e); throw new DeviceTypeMgtPluginException(msg, e); } finally { DeviceTypeUtils.cleanupResources(stmt, null); } return status; }
From source file:com.pactera.edg.am.metamanager.extractor.dao.helper.CreateDependencyHelper.java
private void myDoInPreparedStatement(long sysTime, MMDDependency dependency, PreparedStatement ps) throws SQLException { String ownerModelId = dependency.getOwnerMetadata().getClassifierId(); String valueModelId = dependency.getValueMetadata().getClassifierId(); try {//w w w . ja va2 s. c om // ?ID ps.setString(1, dependency.getOwnerMetadata().getId()); // ?ID ps.setString(2, ownerModelId); // ?ID ps.setString(3, dependency.getValueMetadata().getId()); // ?ID ps.setString(4, valueModelId); // ??? ps.setString(5, dependency.getCode()); // ps.setLong(6, sysTime); ps.setString(7, "1"); ps.setString(8, "1"); setPs(ps, 8); ps.addBatch(); // ?? ps.clearParameters(); if (++super.count % super.batchSize == 0) { ps.executeBatch(); ps.clearBatch(); } } catch (SQLException e) { String logMsg = new StringBuilder().append("?,?:??ID:") .append(dependency.getOwnerMetadata().getId()).append(",?:") .append(ownerModelId).append(",??ID:") .append(dependency.getValueMetadata().getId()).append(",?:") .append(valueModelId).append(", ???:").append(dependency.getCode()).toString(); log.error(logMsg); AdapterExtractorContext.addExtractorLog(ExtractorLogLevel.ERROR, logMsg); throw e; } }
From source file:com.iucosoft.eavertizare.dao.impl.ClientsDaoImpl.java
@Override public void saveLocal(Firma firma, List<Client> clientsList) { String query = "INSERT INTO " + firma.getTabelaClientiLocal() + " VALUES(?, ?, ?, ?, ?, ?, ?, ?)"; Connection con = null;//w ww. j av a2 s. c o m PreparedStatement ps = null; try { con = dataSource.getConnection(); ps = con.prepareStatement(query); // Set auto-commit to false con.setAutoCommit(false); for (Client client : clientsList) { ps.setInt(1, client.getId()); ps.setString(2, client.getNume()); ps.setString(3, client.getPrenume()); ps.setInt(4, client.getNrTelefon()); ps.setString(5, client.getEmail()); ps.setTimestamp(6, (new java.sql.Timestamp(client.getDateExpirare().getTime()))); ps.setInt(7, firma.getId()); ps.setInt(8, 0); ps.addBatch(); } // Create an int[] to hold returned values int[] count = ps.executeBatch(); //Explicitly commit statements to apply changes con.commit(); } catch (SQLException e) { e.printStackTrace(); try { con.rollback(); } catch (SQLException ex) { Logger.getLogger(ClientsDaoImpl.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } }
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;/*w w w .j a v a 2 s. co m*/ 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; }