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:de.static_interface.reallifeplugin.database.AbstractTable.java

public T[] get(String query, Object... paramObjects) throws SQLException {
    query = query.replaceAll("\\Q{TABLE}\\E", getName());
    PreparedStatement statement = db.getConnection().prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
    if (paramObjects != null && paramObjects.length > 0) {
        int i = 1;
        for (Object s : paramObjects) {
            statement.setObject(i, s);
            i++;//from   w  w  w  .j  a  va 2  s .co  m
        }
    }

    return deserialize(statement.executeQuery());
}

From source file:com.hx.sync.service.ThreadCallBackTask.java

public void writeLog(DatabaseUtil dest, TmOvLog log) {
    String sql = " insert into tm_ov_log (sync_type,key_data,sync_log,log_time,sync_status,entity_code,data_node) values (?,?,?,?,?,?,?);";

    List<Object> params = new ArrayList<Object>();
    params.add(log.getSyncType());// ww  w  . ja va 2 s .  co  m
    params.add(log.getKeyData());
    params.add(log.getSyncLog());
    params.add(DateUtil.getCurrentTimestamp());
    params.add(log.getSyncStatus());
    params.add(log.getEntityCode());
    params.add(log.getDataNode());

    Connection conn = dest.getConn();
    PreparedStatement ps = null;
    try {
        ps = conn.prepareStatement(sql);
        for (int i = 0; i < params.size(); i++) {
            ps.setObject(i + 1, params.get(i));
        }
        ps.executeUpdate();

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (ps != null) {

            try {
                ps.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}

From source file:net.ymate.platform.persistence.jdbc.base.AbstractOperator.java

protected void __doSetParameters(PreparedStatement statement) throws SQLException {
    for (int i = 0; i < this.getParameters().size(); i++) {
        SQLParameter _param = this.getParameters().get(i);
        if (_param.getValue() == null) {
            statement.setNull(i + 1, 0);
        } else {/*ww w  . jav  a  2s  .  c om*/
            statement.setObject(i + 1, _param.getValue());
        }
    }
}

From source file:moe.yuna.palinuridae.core.BaseDao.java

/**
 * @param columnValuePair/*from   ww w  .ja v a 2s. com*/
 * @param tableName
 * @return
 * @throws DBUtilException
 */
public Object save(Map<String, Object> columnValuePair, String tableName) throws DBUtilException {
    try {
        final List<Object> paras = new ArrayList<>();
        final String sql = getDialect().insert(tableName, columnValuePair, paras);
        log.debug("insert sql:" + sql);
        int id = 0;
        KeyHolder keyHolder = new GeneratedKeyHolder();
        getJdbcTemplate().update((PrepareStatementCreator) (conn) -> {
            PreparedStatement stat = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            for (int i = 0, size = paras.size(); i < size; i++) {
                stat.setObject(i + 1, paras.get(i));
            }

            return stat;
        }, keyHolder);
        Number key = keyHolder.getKey();
        id = key != null ? key.intValue() : 0;
        return id;
    } catch (DataAccessException ex) {
        throw new DBUtilException(ex);
    }
}

From source file:org.vulpe.model.entity.types.EntityType.java

public void nullSafeSet(final PreparedStatement pstm, final Object value, final int index) throws SQLException {
    final VulpeEntity<?> entity = (VulpeEntity<?>) value;
    if (entity == null || entity.getId() == null) {
        pstm.setNull(index, type);//from ww  w . ja v a  2 s  .  c o m
    } else {
        pstm.setObject(index, entity.getId());
    }
}

From source file:mayoapp.migrations.V0075_0003__update_tenant_configurations.java

@Override
public void migrate(Connection connection) throws Exception {
    connection.setAutoCommit(false);/*from  w w  w  . j ava  2s.  c o  m*/

    Statement queryIdsStatement = connection.createStatement();
    ResultSet tenants = queryIdsStatement.executeQuery("SELECT entity_id, slug, configuration FROM entity "
            + "INNER JOIN tenant ON entity.id = tenant.entity_id");

    Map<UUID, ConfigurationAndName> tenantsData = Maps.newHashMap();

    while (tenants.next()) {
        String json = tenants.getString("configuration");
        String name = tenants.getString("slug");
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> configuration = objectMapper.readValue(json,
                new TypeReference<Map<String, Object>>() {
                });
        if (configuration.containsKey("general")) {
            Map<String, Object> generalConfiguration = (Map<String, Object>) configuration.get("general");
            if (generalConfiguration.containsKey("name")) {
                name = (String) generalConfiguration.get("name");
                ((Map<String, Object>) configuration.get("general")).remove("name");
                json = objectMapper.writeValueAsString(configuration);
            }

        }
        ConfigurationAndName configurationAndName = new ConfigurationAndName(json, name);
        tenantsData.put((UUID) tenants.getObject("entity_id"), configurationAndName);
    }

    queryIdsStatement.close();

    PreparedStatement statement = connection
            .prepareStatement("UPDATE tenant SET name=?, configuration=? WHERE entity_id =?");

    for (UUID id : tenantsData.keySet()) {
        statement.setString(1, tenantsData.get(id).getName());
        statement.setString(2, tenantsData.get(id).getConfiguration());
        statement.setObject(3, new PG_UUID(id));
        statement.addBatch();
    }

    try {
        statement.executeBatch();
    } finally {
        statement.close();
    }
}

From source file:net.solarnetwork.node.dao.jdbc.general.JdbcGeneralLocationDatumDao.java

@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void setDatumUploaded(final GeneralLocationDatum datum, Date date, String destination,
        String trackingId) {//from  w  w  w  .j  a va 2  s . c  om
    final long timestamp = (date == null ? System.currentTimeMillis() : date.getTime());
    getJdbcTemplate().update(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(getSqlResource(SQL_RESOURCE_UPDATE_UPLOADED));
            int col = 1;
            ps.setTimestamp(col++, new java.sql.Timestamp(timestamp));
            ps.setTimestamp(col++, new java.sql.Timestamp(datum.getCreated().getTime()));
            ps.setObject(col++, datum.getLocationId());
            ps.setObject(col++, datum.getSourceId());
            return ps;
        }
    });
}

From source file:com.univocity.app.data.Dao.java

private void execute(final Set<Entry<String, Object>> data, final Set<Entry<String, Object>> matchingEntries,
        final String script) {

    log.debug("Executing SQL: {}", script);

    database.getJdbcTemplate().execute(new ConnectionCallback<Void>() {
        @Override/*from www . j a v  a 2  s.  com*/
        public Void doInConnection(Connection connection) throws SQLException, DataAccessException {
            PreparedStatement statement = connection.prepareStatement(script);
            try {
                int idx = 1;
                for (Entry<String, Object> e : data) {
                    log.debug("Parameter {}: {}", idx, e);
                    statement.setObject(idx++, e.getValue());
                }

                for (Entry<String, Object> e : matchingEntries) {
                    log.debug("Parameter {}: {}", idx, e);
                    statement.setObject(idx++, e.getValue());
                }

                statement.executeUpdate();
            } finally {
                statement.close();
            }

            return null;
        }
    });
}

From source file:org.pasta.apps.form.InvoiceReturn.java

public Vector<Vector<Object>> getData(int orgId, String invoiceFrom, String invoiceTo,
        java.util.Date invoiceDateFrom, java.util.Date invoiceDateTo, int invoiceDocType, int customerId,
        String invoiceSent) {//from   w  w  w  . jav a2 s. co m
    Vector<Vector<Object>> dataL = new Vector<Vector<Object>>();

    List<Object> params = new ArrayList<Object>();

    StringBuffer sql = new StringBuffer(
            "SELECT iv.IsSent , iv.DocumentNo , bp.Name as CustomerName , iv.DateInvoiced , iv.GrandTotal , iv.InvoiceStatusNote , iv.C_Invoice_ID\n");
    sql.append("FROM C_Invoice iv INNER JOIN C_BPartner bp ON iv.C_BPartner_ID = bp.C_BPartner_ID ").append(
            "WHERE iv.IsSOTrx = 'Y' AND iv.DocStatus ='CO' AND iv.AD_Client_ID = ? AND iv.AD_Org_Id = ? \n");

    params.add(Env.getAD_Client_ID(getCtx()));
    params.add(orgId);

    if (!StringUtils.isEmpty(invoiceFrom)) {
        sql.append("AND iv.DocumentNo >= ? ");
        params.add(invoiceFrom);
    }

    if (!StringUtils.isEmpty(invoiceTo)) {
        sql.append("AND iv.DocumentNo <= ? ");
        params.add(invoiceTo);
    }

    if (invoiceDateFrom != null) {
        sql.append("AND iv.DateInvoiced >= ? ");
        java.sql.Date dateFrom = new java.sql.Date(invoiceDateFrom.getTime());
        params.add(dateFrom);
    }

    if (invoiceDateTo != null) {
        sql.append("AND iv.DateInvoiced <= ? ");
        java.sql.Date dateTo = new java.sql.Date(invoiceDateTo.getTime());
        params.add(dateTo);
    }

    if (invoiceDocType > 0) {
        sql.append("AND iv.C_DocType_ID = ? ");
        params.add(invoiceDocType);
    }

    if (customerId > 0) {
        sql.append("AND iv.C_BPartner_ID = ? ");
        params.add(customerId);
    }

    if (!StringUtils.isEmpty(invoiceSent)) {
        sql.append("AND COALESCE(iv.IsSent,'N') = ? ");
        params.add(invoiceSent);
    }

    sql.append("ORDER BY iv.DocumentNo Desc , iv.DateInvoiced ");

    PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
    try {
        int prmIdx = 1;
        for (Object param : params) {
            pstmt.setObject(prmIdx++, param);
        }
        ResultSet rs = pstmt.executeQuery();

        while (rs.next()) {
            ids.put(rs.getString("DocumentNo"), rs.getInt("C_Invoice_ID"));

            Vector<Object> line = new Vector<Object>(7);
            line.add(new Boolean(false));

            KeyNamePair pp = new KeyNamePair(rs.getInt("C_Invoice_ID"), rs.getString("DocumentNo"));
            line.add(pp);
            line.add(rs.getString("CustomerName"));
            line.add(rs.getTimestamp("DateInvoiced"));
            line.add(rs.getBigDecimal("GrandTotal"));
            line.add(StringUtils.defaultIfEmpty(rs.getString("InvoiceStatusNote"), ""));
            line.add(new Boolean("Y".equals(rs.getString("IsSent"))));

            dataL.add(line);
        }
        rs.close();
        pstmt.close();
    } catch (Exception ex) {
        log.log(Level.SEVERE, sql.toString(), ex);
    }

    return dataL;
}

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

public <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... params) {
    PreparedStatement st = null;
    ResultSet rs = null;//w  w w. jav  a 2 s.c  o  m

    if (log.isDebugEnabled()) {
        log.debug("QUERY:" + sql + " with " + ArrayUtils.toString(params));
    }
    try {
        st = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; ++i) {
            st.setObject(i + 1, params[i]);
        }
        rs = st.executeQuery();
        return new RowMapperResultSetExtractor<T>(rowMapper).extractData(rs);
    } catch (SQLException e) {
        throw new StorageException(e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                // silent
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                // silent
            }
        }
    }

}