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:org.apache.phoenix.hive.PhoenixHiveDBWritable.java

public void write(PreparedStatement statement) throws SQLException {
    for (int i = 0; i < this.values.size(); i++) {
        Object o = this.values.get(i);
        try {//from  ww  w . j av a 2s.c  o  m
            if (o != null) {
                LOG.debug(" value " + o.toString() + " type " + this.PDataTypes[i].getSqlTypeName()
                        + " int value " + this.PDataTypes[i].getSqlType());
                statement.setObject(i + 1,
                        PDataType.fromTypeId(this.PDataTypes[i].getSqlType()).toObject(o.toString()));
            } else {
                LOG.debug(" value NULL  type " + this.PDataTypes[i].getSqlTypeName() + " int value "
                        + this.PDataTypes[i].getSqlType());
                statement.setNull(i + 1, this.PDataTypes[i].getSqlType());
            }
        } catch (RuntimeException re) {
            throw new RuntimeException(String.format("Unable to process column %s, innerMessage=%s",
                    new Object[] { re.getMessage() }), re);
        }
    }
}

From source file:com.mechanicshop.service.SearchServiceImpl.java

@Override
public void insertIntoUnknownTable(Item item) {
    String sql = "INSERT INTO  cars_unknown (Tag,Phone,Name,"
            + "Vehicle,LicensePlate,Vin,InShop,OutShop,Status,Mileage,Picked,Payment,"
            + "Remarks,Rebuilder,Installer,FirstCheckBy,SecondCheckBy,FirstCheckDate,"
            + "SecondCheckDate,Media,Media2,ReferedBy,WarrantyLimit,Warranty,SMS,Comeback," + " DateDeleted)"
            + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    Connection conn = null;//from   www . j  a  v a2s  .  c o  m

    try {
        conn = dataSource.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setObject(1, item.getItemProperty("Tag").getValue());
        ps.setObject(2, item.getItemProperty("Phone").getValue());
        ps.setObject(3, item.getItemProperty("Name").getValue());
        ps.setObject(4, item.getItemProperty("Vehicle").getValue());
        ps.setObject(5, item.getItemProperty("LicensePlate").getValue());
        ps.setObject(6, item.getItemProperty("Vin").getValue());
        ps.setObject(7, item.getItemProperty("InShop").getValue());
        ps.setObject(8, item.getItemProperty("OutShop").getValue());
        ps.setObject(9, item.getItemProperty("Status").getValue());
        ps.setObject(10, item.getItemProperty("Mileage").getValue());
        ps.setObject(11, item.getItemProperty("Picked").getValue());
        ps.setObject(12, item.getItemProperty("Payment").getValue());
        ps.setObject(13, item.getItemProperty("Remarks").getValue());
        ps.setObject(14, item.getItemProperty("Rebuilder").getValue());
        ps.setObject(15, item.getItemProperty("Installer").getValue());
        ps.setObject(16, item.getItemProperty("FirstCheckBy").getValue());
        ps.setObject(17, item.getItemProperty("SecondCheckBy").getValue());
        ps.setObject(18, item.getItemProperty("FirstCheckDate").getValue());
        ps.setObject(19, item.getItemProperty("SecondCheckDate").getValue());
        ps.setObject(20, item.getItemProperty("Media").getValue());
        ps.setObject(21, item.getItemProperty("Media2").getValue());
        ps.setObject(22, item.getItemProperty("ReferedBy").getValue());
        ps.setObject(23, item.getItemProperty("WarrantyLimit").getValue());
        ps.setObject(24, item.getItemProperty("Warranty").getValue());
        ps.setObject(25, item.getItemProperty("SMS").getValue());
        ps.setObject(26, item.getItemProperty("Comeback").getValue());
        ps.setObject(27, new Date());
        ps.executeUpdate();

        ps.close();

    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
}

From source file:eu.java.pg.jsonb.types.JSONBUserType.java

@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
        throws HibernateException, SQLException {
    try {//from  ww  w.j  a va 2s. c o m
        final String json = value == null ? null : objectMapper.writeValueAsString(value);
        PGobject pgo = new PGobject();
        pgo.setType(JSONB_TYPE);
        pgo.setValue(json);
        st.setObject(index, pgo);
    } catch (JsonProcessingException e) {
        throw new HibernateException(e);
    }
}

From source file:org.ala.dao.DocumentDAOImpl.java

/**
 * Save this document to the repository.
 * // w w  w  .  j a va  2 s .c  om
 * @param docs
 */
public void update(final Document doc) {
    getJdbcTemplate().update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            PreparedStatement ps = conn.prepareStatement("update document set "
                    + "file_path=?,mime_type=?,modified=?,parent_document_id=? " + "where id=?");
            ps.setString(1, doc.getFilePath());
            ps.setString(2, doc.getMimeType());
            ps.setObject(3, new Date());
            ps.setObject(4, doc.getParentDocumentId());
            ps.setInt(5, doc.getId());
            return ps;
        }
    });
}

From source file:hermes.store.schema.DefaultJDBCAdapter.java

private PreparedStatement createPreparedStatement(Connection connection, String sql, Object[] params)
        throws SQLException {
    final PreparedStatement stmt = connection.prepareStatement(sql);

    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            if (params[i] != null) {
                stmt.setObject(i + 1, params[i]);
            } else {
                stmt.setNull(i + 1, Types.OTHER);
            }//from w  w w. j  a  va 2s.  com
        }
    }

    return stmt;
}

From source file:com.aw.core.dao.AWQueryExecuter.java

private <Rsl> List<Rsl> executeSQL(RowHandler<Rsl> rowHandler) {
    try {/*  w  w w . j a v  a  2 s . c om*/
        PreparedStatement stmt = connection.prepareStatement(sql);
        if (sqlParams != null)
            for (int i = 0; i < sqlParams.length; i++) {
                Object sqlParam = sqlParams[i];
                if (sqlParam == null)
                    stmt.setNull(i + 1, Types.VARCHAR);
                else
                    stmt.setObject(i + 1, sqlParam);

            }
        List<Rsl> results = new ArrayList<Rsl>(AWQueryAbortable.DEF_LIST_SIZE);
        if (logger.isDebugEnabled())
            logger.debug(DAOSql.buildSQL(sql, sqlParams));
        ResultSet rs = stmt.executeQuery();
        AWQueryAbortable queryAbortable = AWQueryAbortable.instance();
        queryAbortable.resetRowCount();
        while (rs.next()) {
            if (queryAbortable.isAborted())
                break;
            Rsl rsl = rowHandler.handle(rs);
            results.add(rsl);
            queryAbortable.incRowCount();
        }
        logger.debug("Results :" + results.size() + " abortedQuery:" + queryAbortable.isAborted());
        rs.close();
        stmt.close();
        return results;
    } catch (Exception e) {
        logger.error("SQL:" + sql);
        throw AWBusinessException.wrapUnhandledException(logger, e);
    }
}

From source file:com.microsoft.tfs.core.internal.db.DBStatement.java

private void setParameters(final PreparedStatement ps, final Object args) throws SQLException {
    if (args == null) {
        return;//from www  . j  a v a 2 s.  com
    }

    if (!args.getClass().isArray()) {
        ps.setObject(1, args);
    } else {
        final int len = Array.getLength(args);
        for (int i = 0; i < len; i++) {
            ps.setObject(i + 1, Array.get(args, i));
        }
    }
}

From source file:och.comp.db.base.universal.UniversalQueries.java

private int updateRows(UpdateRows update, Connection conn) throws SQLException {

    lastQuery.remove();//from  ww  w. j  a v a2  s .c  o m

    int size = update.fields == null ? 0 : update.fields.length;
    if (size == 0)
        return 0;

    StringBuilder sb = new StringBuilder();
    sb.append("UPDATE ").append(update.table);
    sb.append("\n SET");
    boolean isFirst = true;
    for (RowField<?> q : update.fields) {
        if (!isFirst)
            sb.append(',');
        isFirst = false;
        sb.append(' ').append(q.fieldName()).append("=?");
    }
    WhereCondition condition = update.whereCondition;
    appendWhereCondition(sb, condition);

    String q = sb.toString();
    lastQuery.set(q);

    PreparedStatement ps = conn.prepareStatement(q);
    for (int i = 0; i < size; i++) {
        ps.setObject(i + 1, update.fields[i].value);
    }
    if (!isEmpty(condition) && !isEmpty(condition.values())) {
        RowField<?>[] values = condition.values();
        for (int i = 0; i < values.length; i++) {
            ps.setObject(size + i + 1, values[i].value);
        }
    }

    long start = System.currentTimeMillis();
    logQueryStart(q);

    int out = ps.executeUpdate();
    ps.close();

    logQueryEnd(start);

    return out;

}

From source file:net.solarnetwork.node.dao.jdbc.AbstractJdbcDatumDao.java

/**
 * Mark a Datum as uploaded./*from w  ww  .  j a  v a 2  s .c o m*/
 * 
 * <p>
 * This method will execute the {@link #SQL_RESOURCE_UPDATE_UPLOADED} SQL
 * setting the following parameters:
 * </p>
 * 
 * <ol>
 * <li>Timestamp parameter based on {@code timestamp}</li>
 * <li>Timestamp parameter based on {@code created}</li>
 * <li>Object parameter based on {@code id}</li>
 * </ol>
 * 
 * @param created
 *        the date the object was created
 * @param id
 *        the object's source or location ID
 * @param timestamp
 *        the date the upload happened
 */
protected void updateDatumUpload(final long created, final Object id, final long timestamp) {
    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(created));
            ps.setObject(col++, id);
            return ps;
        }
    });
}

From source file:och.comp.db.base.universal.UniversalQueries.java

private int createRow(CreateRow update, Connection conn) throws SQLException {

    lastQuery.remove();/*w  w w .j  a v  a2  s. c o  m*/

    int size = update.fields == null ? 0 : update.fields.length;
    if (size == 0)
        return 0;

    StringBuilder sb = new StringBuilder();
    sb.append("INSERT INTO ").append(update.table).append(" (");
    {
        boolean isFirst = true;
        for (RowField<?> q : update.fields) {
            if (!isFirst)
                sb.append(',');
            isFirst = false;
            sb.append(' ').append(q.fieldName());
        }
    }
    sb.append(")\n VALUES (");
    {
        boolean isFirst = true;
        for (int i = 0; i < size; i++) {
            if (!isFirst)
                sb.append(',');
            isFirst = false;
            sb.append('?');
        }
    }
    sb.append(")");

    String q = sb.toString();
    lastQuery.set(q);

    PreparedStatement ps = conn.prepareStatement(q);
    for (int i = 0; i < size; i++) {
        ps.setObject(i + 1, update.fields[i].value);
    }

    long start = System.currentTimeMillis();
    logQueryStart(q);

    int out = ps.executeUpdate();
    ps.close();

    logQueryEnd(start);

    return out;

}