Example usage for java.sql PreparedStatement setObject

List of usage examples for java.sql PreparedStatement setObject

Introduction

In this page you can find the example usage for java.sql PreparedStatement setObject.

Prototype

void setObject(int parameterIndex, Object x) throws SQLException;

Source Link

Document

Sets the value of the designated parameter using the given object.

Usage

From source file:guru.bubl.module.neo4j_graph_manipulator.graph.Neo4jFriendlyResource.java

@Override
public void createUsingInitialValues(Map<String, Object> values) {
    Map<String, Object> creationProps = addCreationProperties(values);
    String query = String.format("create (n:%s {1})", GraphElementType.resource);
    NoExRun.wrap(() -> {/*from  w w  w .  j a  v  a2  s.c o  m*/
        PreparedStatement statement = connection.prepareStatement(query);
        statement.setObject(1, creationProps);
        return statement.execute();
    }).get();
}

From source file:com.splicemachine.test_dao.JDBCTemplate.java

private void setArgs(PreparedStatement preparedStatement, Object[] args) throws SQLException {
    if (args != null) {
        for (int i = 0; i < args.length; i++) {
            preparedStatement.setObject(i + 1, args[i]);
        }/*from ww  w.ja  va  2  s  .  c o m*/
    }
}

From source file:mayoapp.migrations.V0300_1005__extract_image_metadata_retroactively.java

@Override
public void migrate(Connection connection) throws Exception {
    ImageProcessor imageProcessor = new DefaultImageProcessor();
    ImageDimensionsMetadataExtractor extractor = new ImageDimensionsMetadataExtractor(imageProcessor);

    StatementContext context = new StatementContextStub();
    connection.setAutoCommit(false);//from  ww w  .  ja  v  a  2s.c o m
    Statement countStatement = connection.createStatement();

    Integer count = 0;
    ResultSet res = countStatement
            .executeQuery("SELECT COUNT(*) FROM attachment JOIN entity on attachment.entity_id = entity.id"); //WHERE parent_id is not null
    while (res.next()) {
        count = res.getInt(1);
    }
    countStatement.close();

    Integer i = 0;

    Map<UUID, Object> toSave = new HashMap<>();

    for (int offset = 0; offset < count; offset += 50) {
        Statement queryStatement = connection.createStatement();
        ResultSet data = queryStatement.executeQuery(
                "SELECT * from attachment JOIN entity on attachment.entity_id = entity.id LIMIT 50 OFFSET "
                        + offset);

        while (data.next()) {
            LoadedAttachmentMapper mapper = new LoadedAttachmentMapper();
            LoadedAttachment attachment = mapper.map(0, data, context);

            logger.info("Processing attachment " + i + " : " + attachment.getFilename());

            Optional<Map<String, Object>> metadata = extractor.extractMetadata(attachment);

            if (metadata.isPresent()) {
                Map<String, Map<String, Object>> meta = new HashMap<>(attachment.getMetadata());
                meta.put("imageDimensions", metadata.get());
                toSave.put(attachment.getId(), meta);
            }

            i++;
        }

        queryStatement.close();
    }

    ObjectMapper mapper = new ObjectMapper();
    PreparedStatement statement = connection
            .prepareStatement("UPDATE attachment SET metadata = CAST (? AS json) WHERE entity_id =?");

    for (UUID attachment : toSave.keySet()) {
        statement.setObject(2, new PG_UUID(attachment));
        statement.setObject(1, mapper.writeValueAsString(toSave.get(attachment)));
        statement.addBatch();
        logger.info("Adding image to batch " + i + " : " + attachment.toString());
    }

    statement.executeBatch();
}

From source file:de.static_interface.reallifeplugin.database.AbstractTable.java

public void executeUpdate(String sql, @Nullable Object... paramObjects) throws SQLException {
    sql = sql.replaceAll("\\Q{TABLE}\\E", getName());
    try {//from  w ww.  j  a v a 2 s  .  c om
        PreparedStatement statment = db.getConnection().prepareStatement(sql);
        if (paramObjects != null) {
            int i = 1;
            for (Object s : paramObjects) {
                statment.setObject(i, s);
                i++;
            }
        }
        statment.executeUpdate();
    } catch (SQLException e) {
        ReallifeMain.getInstance().getLogger()
                .severe("Couldn't execute SQL update: " + sqlToString(sql, paramObjects));
        throw e;
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.db.H2Functions.java

public static String getReadAcl(Connection conn, String id) throws SQLException {
    StringBuffer readAcl = new StringBuffer();

    PreparedStatement ps1 = null;
    PreparedStatement ps2 = null;
    try {//from   w w  w. j  a v a2s . c o  m
        ps1 = conn.prepareStatement("SELECT PARENTID FROM HIERARCHY WHERE ID = ?;");
        boolean first = true;
        do {
            // local acl
            String localReadAcl = getLocalReadAcl(conn, id);
            if (localReadAcl != null && (localReadAcl.length() > 0)) {
                if (readAcl.length() == 0) {
                    readAcl.append(localReadAcl);
                } else {
                    readAcl.append(',' + localReadAcl);
                }
            }
            // get parent
            ps1.setObject(1, id);
            ResultSet rs = ps1.executeQuery();
            String newId;
            if (rs.next()) {
                newId = (String) rs.getObject(1);
                if (rs.wasNull()) {
                    newId = null;
                }
            } else {
                // no such id
                newId = null;
            }
            if (first && newId == null) {
                // there is no parent for the first level
                // we may have a version on our hands, find the live doc
                ps2 = conn.prepareStatement("SELECT VERSIONABLEID FROM VERSIONS WHERE ID = ?;");
                ps2.setObject(1, id);
                rs = ps2.executeQuery();
                if (rs.next()) {
                    newId = (String) rs.getObject(1);
                    if (rs.wasNull()) {
                        newId = null;
                    }
                } else {
                    // no such id
                    newId = null;
                }
            }
            first = false;
            id = newId;
        } while (id != null);
    } finally {
        if (ps1 != null) {
            ps1.close();
        }
        if (ps2 != null) {
            ps2.close();
        }
    }
    return readAcl.toString();
}

From source file:org.netxilia.spi.impl.storage.db.sql.DefaultConnectionWrapper.java

public int update(String sql, Object... params) {
    PreparedStatement st = null;

    long t1 = System.currentTimeMillis();

    try {/*from ww w .j  a v  a 2 s .  c o  m*/
        st = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; ++i) {
            st.setObject(i + 1, params[i]);
        }
        return st.executeUpdate();
    } catch (SQLException e) {
        throw new StorageException(e);
    } finally {
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                // silent
            }
        }
        long t2 = System.currentTimeMillis();
        if (log.isDebugEnabled()) {
            log.debug("UPDATE:" + sql + " with " + ArrayUtils.toString(params) + " update:" + (t2 - t1));
        }
    }
}

From source file:com.github.woozoo73.test.dummy.ProcessorTest.java

private int executeUpdate(String sql, Object[] args) {
    int result = 0;
    Connection con = null;//from  w w w. j  av  a2  s  .  c o  m
    PreparedStatement ps = null;

    try {
        con = getConnection();
        ps = con.prepareStatement(sql);
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
        }

        result = ps.executeUpdate();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
            }
        }
    }

    return result;
}

From source file:com.datatorrent.contrib.enrich.JDBCLoader.java

protected Object getQueryResult(Object key) {
    try {/*from   ww w  .j  av a 2  s  .  c o  m*/
        PreparedStatement getStatement = getConnection().prepareStatement(queryStmt);
        ArrayList<Object> keys = (ArrayList<Object>) key;
        for (int i = 0; i < keys.size(); i++) {
            getStatement.setObject(i + 1, keys.get(i));
        }
        return getStatement.executeQuery();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.sinet.gage.dao.DomainsRepository.java

/**
 * /*from   w  w  w.  j ava  2  s .  com*/
 * @param domains
 */
public void insertDomains(List<Domain> domains) {
    try {
        jdbcTemplate.batchUpdate(DOMAINS_INSERT_SQL, new BatchPreparedStatementSetter() {

            public int getBatchSize() {
                if (domains == null)
                    return 0;
                return domains.size();
            }

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                Domain domain = domains.get(i);
                ps.setLong(1, domain.getDomainId());
                ps.setObject(2, domain.getGuid());
                ps.setString(3, domain.getDomainName());
                ps.setString(4, domain.getLoginPrefix());
                ps.setLong(5, domain.getFlag());
                ps.setString(6, domain.getDomainType());
                ps.setLong(7, domain.getParentDomainId());
                ps.setString(8, domain.getParentDomainName());
                ps.setLong(9, domain.getStateDomainId());
                ps.setString(10, domain.getStateDomainName());
                ps.setString(11, domain.getLicenseType());
                ps.setString(12, domain.getLicensePoolType());
                ps.setInt(13, domain.getNoOfLicense());
                ps.setBoolean(14, domain.isPilot());
                ps.setDate(15, domain.getPilotStartDate());
                ps.setDate(16, domain.getPilotEndDate());
                ps.setBoolean(17, domain.isFullSubscription());
                ps.setObject(18, domain.getSubscriptionStartDate());
                ps.setObject(19, domain.getSubscriptionEndDate());
                ps.setLong(20, domain.getCreatorUserId());
                ps.setTimestamp(21, domain.getCreationDate());
                ps.setLong(22, domain.getModifierUserId());
                ps.setTimestamp(23, domain.getModifiedDate());
            }
        });
    } catch (Exception e) {
        log.error("Error in inserting Domains", e);
    }
}

From source file:com.anyuan.thomweboss.persistence.jdbcimpl.user.UserDaoJdbcImpl.java

@Override
public boolean save(User entity) {
    Connection conn = getConnection();
    boolean result = false;

    String userSql = "insert into t_user (f_username, f_nickname, f_loginname, f_password, "
            + "f_birthday, f_gender, f_createtime, f_logintime, f_roleid, f_contactid, "
            + "f_description) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    try {/*from   w  ww .j a v  a2s.  co  m*/
        conn.setAutoCommit(false);
        Contact contact = entity.getContact();

        Address address = contact.getAddress();
        saveAddress(conn, address); // address id not modify, Addressgettersetter

        Phone phone = contact.getPhone();
        savePhone(conn, phone);

        saveContact(conn, contact);

        PreparedStatement preState = conn.prepareStatement(userSql);
        preState.setObject(1, entity.getUsername());
        preState.setString(2, entity.getNickname());
        preState.setString(3, entity.getLoginname());
        preState.setString(4, entity.getPassword());
        preState.setObject(5, entity.getBirthday());
        preState.setObject(6, entity.getGender());
        preState.setObject(7, entity.getCreatetime());
        preState.setObject(8, entity.getLogintime()); // ?
        preState.setObject(9, null);
        preState.setObject(10, entity.getContact().getId());
        preState.setObject(11, entity.getDescription());
        result = preState.execute();
        conn.commit();

    } catch (SQLException e) {
        e.printStackTrace();
        try {
            conn.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    return result;
}