/** * Execute the given update operation of the given triples. * * @param conn The connection to execute the update on. * @param triples The triples to add or delete. * @param delete Boolean indicating whether the operation is an add or delete. * @throws ModificationException if the operation fails for any reason. */ private void updateTriples( final Connection conn, final Iterator<Triple> triples, final boolean delete) throws ModificationException { Map<PredicateNode, PreparedStatement> statements = new HashMap<PredicateNode, PreparedStatement>(); try { while (triples.hasNext()) { Triple triple = triples.next(); if (LOG.isDebugEnabled()) { String prefix; if (delete) { prefix = "Deleting "; } else { prefix = "Adding "; } LOG.debug(prefix + triple.toString()); } PredicateNode predicate = triple.getPredicate(); PreparedStatement statement = statements.get(predicate); if (statement == null) { String table = _tableManager.getOrMapTableFor(predicate); String sql; if (delete) { sql = "DELETE FROM " + table + " WHERE s = ? AND o = ?"; } else { sql = "INSERT INTO " + table + " (s, o) VALUES (?, ?)"; } statement = conn.prepareStatement(sql); statements.put(predicate, statement); } statement.setString(1, triple.getSubject().toString()); statement.setString(2, triple.getObject().toString()); statement.execute(); } } catch (SQLException e) { throw new ModificationException("Database update failed", e); } finally { // close all statements we created for this update Iterator<PreparedStatement> iter = statements.values().iterator(); while (iter.hasNext()) { PreparedStatement statement = iter.next(); try { statement.close(); } catch (SQLException e) { LOG.warn("unable to close statement", e); } } } }