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:net.lightbody.bmp.proxy.jetty.http.JDBCUserRealm.java

private void loadUser(String username) {
    try {/*from  www  . java  2 s  . c  om*/
        if (null == _con)
            connectDatabase();

        if (null == _con)
            throw new SQLException("Can't connect to database");

        PreparedStatement stat = _con.prepareStatement(_userSql);
        stat.setObject(1, username);
        ResultSet rs = stat.executeQuery();

        if (rs.next()) {
            Object key = rs.getObject(_userTableKey);
            put(username, rs.getString(_userTablePasswordField));
            stat.close();

            stat = _con.prepareStatement(_roleSql);
            stat.setObject(1, key);
            rs = stat.executeQuery();

            while (rs.next())
                addUserToRole(username, rs.getString(_roleTableRoleField));

            stat.close();
        }
    } catch (SQLException e) {
        log.warn("UserRealm " + getName() + " could not load user information from database", e);
        connectDatabase();
    }
}

From source file:com.adaptris.core.services.jdbc.TypedStatementParameter.java

@Override
public final void apply(int parameterIndex, PreparedStatement statement, AdaptrisMessage msg)
        throws SQLException {
    Object o = getQueryValue(msg);
    T typedParam = convert(o);/*from w w w. j  a v a2s  .c  om*/
    logger().log(parameterIndex, typedParam);
    statement.setObject(parameterIndex, typedParam);
}

From source file:com.adaptris.core.services.jdbc.TimestampStatementParameter.java

@Override
public void apply(int parameterIndex, PreparedStatement statement, AdaptrisMessage msg)
        throws SQLException, ServiceException {
    log.trace("Setting argument {} to [{}]", parameterIndex, getQueryValue(msg));
    statement.setObject(parameterIndex, this.toDate(getQueryValue(msg)));
}

From source file:net.bitnine.agensgraph.test.ReturnTest.java

public void testSimpleBind() throws Exception {
    ResultSet rs;/*www  .j  a v a2 s .  com*/
    PreparedStatement pstmt = con.prepareStatement("RETURN ?");

    Jsonb data = new Jsonb();
    data.setJsonValue(JsonObject.create("{\"name\":\"ktlee\"}"));
    pstmt.setObject(1, data);
    rs = pstmt.executeQuery();
    while (rs.next()) {
        JsonObject jo = ((Jsonb) rs.getObject(1)).getJsonObject();
        assertEquals("ktlee", jo.getString("name"));
    }
    rs.close();

    Map<String, Object> jobj = new HashMap<>();
    jobj.put("name", "ktlee");
    jobj.put("age", 41);
    data.setJsonValue(JsonObject.create(jobj));
    pstmt.setObject(1, data);
    rs = pstmt.executeQuery();
    while (rs.next()) {
        JsonObject jo = ((Jsonb) rs.getObject(1)).getJsonObject();
        assertEquals(41, jo.getInt("age").intValue());
    }
    rs.close();

    JsonObject jo = JsonObject.create(jobj);
    jo.put("id", JsonArray.create(1, 2, 3));
    pstmt.setObject(1, jo);
    rs = pstmt.executeQuery();
    while (rs.next()) {
        jo = ((Jsonb) rs.getObject(1)).getJsonObject();
        assertEquals(3, (int) jo.getArray("id").getInt(2));
    }
    rs.close();

    data.setJsonValue(10);
    pstmt.setObject(1, data);
    rs = pstmt.executeQuery();
    while (rs.next()) {
        assertEquals(10, (int) ((Jsonb) rs.getObject(1)).getInt());
    }
    rs.close();
    pstmt.close();
}

From source file:ru.org.linux.user.ProfileDao.java

public void writeProfile(@Nonnull final User user, @Nonnull final Profile profile) {
    String boxlets[] = null;//ww w .  ja  va  2s.  co  m

    List<String> customBoxlets = profile.getCustomBoxlets();

    if (customBoxlets != null) {
        boxlets = customBoxlets.toArray(new String[customBoxlets.size()]);
    }

    final String[] finalBoxlets = boxlets;
    if (jdbcTemplate.update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement st = con
                    .prepareStatement("UPDATE user_settings SET settings=?, main=? WHERE id=?");

            st.setObject(1, profile.getSettings());

            if (finalBoxlets != null) {
                st.setArray(2, con.createArrayOf("text", finalBoxlets));
            } else {
                st.setNull(2, Types.ARRAY);
            }

            st.setInt(3, user.getId());

            return st;
        }
    }) == 0) {
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement st = con
                        .prepareStatement("INSERT INTO user_settings (id, settings, main) VALUES (?,?,?)");

                st.setInt(1, user.getId());

                st.setObject(2, profile.getSettings());

                if (finalBoxlets != null) {
                    st.setArray(3, con.createArrayOf("text", finalBoxlets));
                } else {
                    st.setNull(3, Types.ARRAY);
                }

                return st;
            }
        });
    }
}

From source file:org.eclipse.ecr.core.storage.sql.extensions.H2Functions.java

/**
 * Adds an invalidation from this cluster node to the invalidations list.
 *//*w ww  . jav a  2s  . c  om*/
@SuppressWarnings("boxing")
public static void clusterInvalidateString(Connection conn, String id, String fragments, int kind)
        throws SQLException {
    PreparedStatement ps = null;
    try {
        // find other node ids
        String sql = "SELECT \"NODEID\" FROM \"CLUSTER_NODES\" " + "WHERE \"NODEID\" <> SESSION_ID()";
        if (isLogEnabled()) {
            logDebug(sql);
        }
        ps = conn.prepareStatement(sql);
        List<Long> nodeIds = new LinkedList<Long>();
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            nodeIds.add(rs.getLong(1));
        }
        if (isLogEnabled()) {
            logDebug("  -> " + nodeIds);
        }
        // invalidate
        sql = "INSERT INTO \"CLUSTER_INVALS\" " + "(\"NODEID\", \"ID\", \"FRAGMENTS\", \"KIND\") "
                + "VALUES (?, ?, ?, ?)";
        for (Long nodeId : nodeIds) {
            if (isLogEnabled()) {
                logDebug(sql, nodeId, id, fragments, kind);
            }
            ps = conn.prepareStatement(sql);
            ps.setLong(1, nodeId);
            ps.setObject(2, id);
            ps.setString(3, fragments);
            ps.setInt(4, kind);
            ps.execute();
        }
    } finally {
        if (ps != null) {
            ps.close();
        }
    }
}

From source file:org.projasource.dbimport.bindings.SqlQueryExecutor.java

public String execute(final String sql, final Object[] params, final RSCallback callback) throws SQLException {
    final PreparedStatement ps = conn.prepareStatement(sql);
    try {//  w  w w.  j a  v  a 2  s.  c  om
        if (params != null) {
            for (int i = 1; i <= params.length; i++) {
                ps.setObject(i, params[i]);
            }
        }
        final ResultSet rs = ps.executeQuery();
        try {
            if (callback != null) {
                return callback.fetchResultSet(rs);
            }
            return null;
        } finally {
            rs.close();
        }
    } finally {
        ps.close();
    }
}

From source file:ccc.migration.DbUtilsDB.java

/** {@inheritDoc} */
@Override/*from   w  w  w.j a  v  a  2  s.  co m*/
@SuppressWarnings("unchecked")
public <T> T select(final SqlQuery<T> q, final Object... param) {

    try {
        log.debug("Query: " + q.getSql());
        log.debug("Params: " + Arrays.asList(param));

        final PreparedStatement s = _c.prepareStatement(q.getSql());
        try {
            int index = 1;
            for (final Object o : param) {
                s.setObject(index, o);
                index++;
            }

            log.debug("Running query.");
            final boolean resultsReturned = s.execute();
            log.debug("Running finished.");

            if (!resultsReturned) {
                throw new MigrationException("Query returned no results.");
            }

            final ResultSet rs = s.getResultSet();

            try {
                final Object result = q.handle(rs);
                return (T) result;

            } catch (final SQLException e) {
                throw new MigrationException(e);
            } finally {
                DbUtils.closeQuietly(rs);
            }

        } catch (final SQLException e) {
            throw new MigrationException(e);
        } finally {
            DbUtils.closeQuietly(s);
        }

    } catch (final SQLException e) {
        throw new MigrationException(e);
    }
}

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

/**
 * /*w ww  .  j  a va2  s  . c  o m*/
 * @param domains
 */
public void updateDomains(List<Domain> domains) {
    try {
        jdbcTemplate.batchUpdate(DOMAINS_FULL_UPDATE_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.setObject(1, domain.getGuid());
                ps.setString(2, domain.getDomainName());
                ps.setString(3, domain.getLoginPrefix());
                ps.setLong(4, domain.getFlag());
                ps.setString(5, domain.getDomainType());
                ps.setLong(6, domain.getParentDomainId());
                ps.setString(7, domain.getParentDomainName());
                ps.setLong(8, domain.getStateDomainId());
                ps.setString(9, domain.getStateDomainName());
                ps.setString(10, domain.getLicenseType());
                ps.setString(11, domain.getLicensePoolType());
                ps.setInt(12, domain.getNoOfLicense());
                ps.setBoolean(13, domain.isPilot());
                ps.setDate(14, domain.getPilotStartDate());
                ps.setDate(15, domain.getPilotEndDate());
                ps.setBoolean(16, domain.isFullSubscription());
                ps.setObject(17, domain.getSubscriptionStartDate());
                ps.setObject(18, domain.getSubscriptionEndDate());
                ps.setLong(19, domain.getModifierUserId());
                ps.setTimestamp(20, domain.getModifiedDate());
                ps.setLong(21, domain.getDomainId());
            }
        });
    } catch (Exception e) {
        log.error("Error in updating Domains", e);
    }
}

From source file:guru.bubl.module.neo4j_graph_manipulator.graph.FriendlyResourceNeo4j.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);
    NoEx.wrap(() -> {// w  w  w.  j  av  a  2s .c o  m
        PreparedStatement statement = connection.prepareStatement(query);
        statement.setObject(1, creationProps);
        return statement.execute();
    }).get();
}