Example usage for java.sql PreparedStatement setFloat

List of usage examples for java.sql PreparedStatement setFloat

Introduction

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

Prototype

void setFloat(int parameterIndex, float x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java float value.

Usage

From source file:biblivre3.acquisition.order.BuyOrderDAO.java

public boolean insertBuyOrder(BuyOrderDTO dto) {
    Connection conInsert = null;/*from   w ww  .  jav  a  2 s .  co m*/
    try {
        conInsert = getDataSource().getConnection();
        final String sqlInsert = " INSERT INTO acquisition_order (serial_quotation, order_date, "
                + " responsable, obs, status, invoice_number, "
                + " receipt_date, total_value, delivered_quantity, " + " terms_of_payment, deadline_date) "
                + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); ";
        PreparedStatement pstInsert = conInsert.prepareStatement(sqlInsert);
        pstInsert.setInt(1, dto.getSerialQuotation());
        pstInsert.setDate(2, new java.sql.Date(dto.getOrderDate().getTime()));
        pstInsert.setString(3, dto.getResponsible());
        pstInsert.setString(4, dto.getObs());
        pstInsert.setString(5, dto.getStatus());
        pstInsert.setString(6, dto.getInvoiceNumber());

        Date receiptDate = dto.getReceiptDate();
        if (receiptDate != null) {
            pstInsert.setDate(7, new java.sql.Date(receiptDate.getTime()));
        } else {
            pstInsert.setNull(7, java.sql.Types.DATE);
        }

        Float totalValue = dto.getTotalValue();
        if (totalValue != null) {
            pstInsert.setFloat(8, totalValue);
        } else {
            pstInsert.setNull(8, java.sql.Types.FLOAT);
        }

        Integer deliveryQuantity = dto.getDeliveredQuantity();
        if (deliveryQuantity != null) {
            pstInsert.setInt(9, deliveryQuantity);
        } else {
            pstInsert.setNull(9, java.sql.Types.INTEGER);
        }

        pstInsert.setString(10, dto.getTermsOfPayment());
        pstInsert.setDate(11, new java.sql.Date(dto.getDeadlineDate().getTime()));
        return pstInsert.executeUpdate() > 0;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new DAOException(e.getMessage());
    } finally {
        closeConnection(conInsert);
    }
}

From source file:org.apache.phoenix.query.BaseTest.java

protected static void initSumDoubleValues(byte[][] splits, String url) throws Exception {
    ensureTableCreated(url, "SumDoubleTest", splits);
    Properties props = new Properties();
    Connection conn = DriverManager.getConnection(url, props);
    try {//from   ww  w  .  j  a v a2 s  .  co  m
        // Insert all rows at ts
        PreparedStatement stmt = conn.prepareStatement("upsert into " + "SumDoubleTest(" + "    id, "
                + "    d, " + "    f, " + "    ud, " + "    uf) " + "VALUES (?, ?, ?, ?, ?)");
        stmt.setString(1, "1");
        stmt.setDouble(2, 0.001);
        stmt.setFloat(3, 0.01f);
        stmt.setDouble(4, 0.001);
        stmt.setFloat(5, 0.01f);
        stmt.execute();

        stmt.setString(1, "2");
        stmt.setDouble(2, 0.002);
        stmt.setFloat(3, 0.02f);
        stmt.setDouble(4, 0.002);
        stmt.setFloat(5, 0.02f);
        stmt.execute();

        stmt.setString(1, "3");
        stmt.setDouble(2, 0.003);
        stmt.setFloat(3, 0.03f);
        stmt.setDouble(4, 0.003);
        stmt.setFloat(5, 0.03f);
        stmt.execute();

        stmt.setString(1, "4");
        stmt.setDouble(2, 0.004);
        stmt.setFloat(3, 0.04f);
        stmt.setDouble(4, 0.004);
        stmt.setFloat(5, 0.04f);
        stmt.execute();

        stmt.setString(1, "5");
        stmt.setDouble(2, 0.005);
        stmt.setFloat(3, 0.05f);
        stmt.setDouble(4, 0.005);
        stmt.setFloat(5, 0.05f);
        stmt.execute();

        conn.commit();
    } finally {
        conn.close();
    }
}

From source file:biblivre3.acquisition.order.BuyOrderDAO.java

public boolean updateBuyOrder(BuyOrderDTO dto) {
    Connection conInsert = null;/*  w w  w. jav  a2  s  .c  o  m*/
    try {
        conInsert = getDataSource().getConnection();
        final String sqlInsert = " UPDATE acquisition_order " + " SET serial_quotation = ?, order_date = ?, "
                + " responsable = ?, obs = ?, status = ?, "
                + " invoice_number = ?, receipt_date = ?, total_value = ?, "
                + " delivered_quantity = ?, terms_of_payment = ?, deadline_date=? "
                + " WHERE serial_order = ?;";

        PreparedStatement pstInsert = conInsert.prepareStatement(sqlInsert);
        pstInsert.setInt(1, dto.getSerialQuotation());
        pstInsert.setDate(2, new java.sql.Date(dto.getOrderDate().getTime()));
        pstInsert.setString(3, dto.getResponsible());
        pstInsert.setString(4, dto.getObs());
        pstInsert.setString(5, dto.getStatus() != null && dto.getStatus().equals("1") ? "1" : "0");
        pstInsert.setString(6, dto.getInvoiceNumber());

        Date receiptDate = dto.getReceiptDate();
        if (receiptDate != null) {
            pstInsert.setDate(7, new java.sql.Date(receiptDate.getTime()));
        } else {
            pstInsert.setNull(7, java.sql.Types.DATE);
        }

        Float totalValue = dto.getTotalValue();
        if (totalValue != null) {
            pstInsert.setFloat(8, totalValue);
        } else {
            pstInsert.setNull(8, java.sql.Types.FLOAT);
        }

        Integer deliveryQuantity = dto.getDeliveredQuantity();
        if (deliveryQuantity != null) {
            pstInsert.setInt(9, deliveryQuantity);
        } else {
            pstInsert.setNull(9, java.sql.Types.INTEGER);
        }

        pstInsert.setString(10, dto.getTermsOfPayment());
        pstInsert.setDate(11, new java.sql.Date(dto.getDeadlineDate().getTime()));
        pstInsert.setInt(12, dto.getSerial());
        return pstInsert.executeUpdate() > 0;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new DAOException(e.getMessage());
    } finally {
        closeConnection(conInsert);
    }
}

From source file:org.accada.epcis.repository.capture.CaptureOperationsBackendSQL.java

/**
 * {@inheritDoc}// w  w  w.j a  v  a2  s . com
 */
public void insertExtensionFieldsForEvent(final CaptureOperationsSession session, final long eventId,
        final String eventType, final List<EventFieldExtension> exts) throws SQLException {
    for (EventFieldExtension ext : exts) {
        String insert = "INSERT INTO event_" + eventType + "_extensions " + "(event_id, fieldname, prefix, "
                + ext.getValueColumnName() + ") VALUES (?, ? ,?, ?)";
        PreparedStatement ps = session.getBatchInsert(insert);
        if (LOG.isDebugEnabled()) {
            LOG.debug("INSERT: " + insert);
            LOG.debug("       insert param 1: " + eventId);
            LOG.debug("       insert param 2: " + ext.getFieldname());
            LOG.debug("       insert param 3: " + ext.getPrefix());
            LOG.debug("       insert param 4: " + ext.getStrValue());
        }
        ps.setLong(1, eventId);
        ps.setString(2, ext.getFieldname());
        ps.setString(3, ext.getPrefix());
        if (ext.getIntValue() != null) {
            ps.setInt(4, ext.getIntValue().intValue());
        } else if (ext.getFloatValue() != null) {
            ps.setFloat(4, ext.getFloatValue().floatValue());
        } else if (ext.getDateValue() != null) {
            ps.setTimestamp(4, ext.getDateValue());
        } else {
            ps.setString(4, ext.getStrValue());
        }
        ps.addBatch();
    }
}

From source file:com.liferay.portal.upgrade.util.Table.java

public void setColumn(PreparedStatement ps, int index, Integer type, String value) throws Exception {

    int t = type.intValue();

    int paramIndex = index + 1;

    if (t == Types.BIGINT) {
        ps.setLong(paramIndex, GetterUtil.getLong(value));
    } else if (t == Types.BOOLEAN) {
        ps.setBoolean(paramIndex, GetterUtil.getBoolean(value));
    } else if ((t == Types.CLOB) || (t == Types.VARCHAR)) {
        value = StringUtil.replace(value, SAFE_CHARS[1], SAFE_CHARS[0]);

        ps.setString(paramIndex, value);
    } else if (t == Types.DOUBLE) {
        ps.setDouble(paramIndex, GetterUtil.getDouble(value));
    } else if (t == Types.FLOAT) {
        ps.setFloat(paramIndex, GetterUtil.getFloat(value));
    } else if (t == Types.INTEGER) {
        ps.setInt(paramIndex, GetterUtil.getInteger(value));
    } else if (t == Types.SMALLINT) {
        ps.setShort(paramIndex, GetterUtil.getShort(value));
    } else if (t == Types.TIMESTAMP) {
        if (StringPool.NULL.equals(value)) {
            ps.setTimestamp(paramIndex, null);
        } else {// ww  w.ja va  2  s . c  om
            DateFormat df = DateUtil.getISOFormat();

            ps.setTimestamp(paramIndex, new Timestamp(df.parse(value).getTime()));
        }
    } else {
        throw new UpgradeException("Upgrade code using unsupported class type " + type);
    }
}

From source file:org.pegadi.server.article.ArticleServerImpl.java

/**
 * Saves a new or updates an existing article. If the articleID is 0, a new article is inserted into the database
 * and the new ID is returned. Else the article will be updated. This method will not save or modyify
 * the article text. The exception is when the article type changes.
 *
 * @param article The article to save./* ww  w .j  a  va  2s  .  c o m*/
 * @return New articleID if new article is created or 0 for successful save of existing article. Returnvalue less than 0
 *         means that something was wrong, and the article was not successfully saved.
 */
public int saveArticle(final Article article) {
    if (article == null) { // huh - no article?
        log.error("error - can't save a non-exixting article...");
        return -1;
    } else {
        log.info("Saving article with ID=" + article.getId());

        final String journalist = article.getJournalist() != null ? article.getJournalist().getUsername()
                : null;
        final String photographer = article.getPhotographer() != null ? article.getPhotographer().getUsername()
                : null;
        final int publication = article.getPublication() != null ? article.getPublication().getId() : 0;
        final int articleType = article.getArticleType() != null ? article.getArticleType().getId() : 0;
        final String text = article.getText() != null ? article.getText() : "";
        final int department = article.getSection() != null ? article.getSection().getId() : 0;
        final int articlestatus = article.getArticleStatus() != null ? article.getArticleStatus().getId() : 1;
        if (article.getId() == 0) { // no ID means insert a new article

            KeyHolder keyHolder = new GeneratedKeyHolder();
            final String insert = "INSERT INTO Article (name, refJournalist, refPhotographer, refPublication, description, refArticleType, wantedCharacters, wantedPages,articlexml, refSection, refStatus, lastSaved) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";

            template.getJdbcOperations().update(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps = connection.prepareStatement(insert, new String[] { "ID" });
                    ps.setString(1, article.getName());
                    ps.setString(2, journalist);
                    ps.setString(3, photographer);
                    ps.setInt(4, publication);
                    ps.setString(5, article.getDescription());
                    ps.setInt(6, articleType);
                    ps.setInt(7, article.getWantedNumberOfCharacters());
                    ps.setFloat(8, article.getWantedNumberOfPages());
                    ps.setString(9, text);
                    ps.setInt(10, department);
                    ps.setInt(11, articlestatus);
                    ps.setTimestamp(12, new Timestamp((new Date()).getTime()));
                    return ps;
                }
            }, keyHolder);
            int articleId = keyHolder.getKey().intValue();
            log.info("Saved a new article, and gave it ID={}", articleId);
            return articleId;
        } else {
            // Save existing article
            int articletypeOld = template.queryForInt("SELECT refArticleType FROM Article WHERE ID=:id",
                    Collections.singletonMap("id", article.getId()));

            if (article.getArticleType() != null) {
                int AT = article.getArticleType().getId();
                // Important to do this before the article text is set
                if (AT != articletypeOld && article.hasText()) {
                    changeArticleType(article, AT);
                }
            }
            doBackup(article.getId(), article.getText());

            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("name", article.getName());
            parameters.put("text", article.getText());
            parameters.put("department", department);
            parameters.put("journalist", journalist);
            parameters.put("photographer", photographer);
            parameters.put("publication", publication);
            parameters.put("description", article.getDescription());
            parameters.put("wantedNumbeOfCharacters", article.getWantedNumberOfCharacters());
            parameters.put("wantedNumberOfPages", article.getWantedNumberOfPages());
            parameters.put("articleType", articleType);
            parameters.put("articleStatus", articlestatus);
            parameters.put("lastSaved", new Timestamp((new Date()).getTime()));
            parameters.put("id", article.getId());
            template.update("UPDATE Article " + "SET name=:name, articlexml=:text, refSection=:department, "
                    + "refJournalist=:journalist, refPhotographer=:photographer, "
                    + "refPublication=:publication, description=:description, "
                    + "wantedCharacters=:wantedNumbeOfCharacters, wantedPages=:wantedNumberOfPages, "
                    + "refArticleType=:articleType, refStatus=:articleStatus, " + "lastSaved=:lastSaved "
                    + "WHERE ID=:id", parameters);
        }
    }

    return 0;
}

From source file:org.wso2.carbon.event.output.adapter.rdbms.RDBMSEventAdapter.java

/**
 * Populating column values to table Insert query
 *//*from w w w .  jav a2s  .c  o m*/
private void populateStatement(Map<String, Object> map, PreparedStatement stmt, List<Attribute> colOrder)
        throws OutputEventAdapterException {
    Attribute attribute = null;

    try {
        for (int i = 0; i < colOrder.size(); i++) {
            attribute = colOrder.get(i);
            Object value = map.get(attribute.getName());
            if (value != null) {
                switch (attribute.getType()) {
                case INT:
                    stmt.setInt(i + 1, (Integer) value);
                    break;
                case LONG:
                    stmt.setLong(i + 1, (Long) value);
                    break;
                case FLOAT:
                    stmt.setFloat(i + 1, (Float) value);
                    break;
                case DOUBLE:
                    stmt.setDouble(i + 1, (Double) value);
                    break;
                case STRING:
                    stmt.setString(i + 1, (String) value);
                    break;
                case BOOL:
                    stmt.setBoolean(i + 1, (Boolean) value);
                    break;
                }
            } else {
                throw new OutputEventAdapterException("Cannot Execute Insert/Update. Null value detected for "
                        + "attribute" + attribute.getName());
            }
        }
    } catch (SQLException e) {
        cleanupConnections(stmt, null);
        throw new OutputEventAdapterException("Cannot set value to attribute name " + attribute.getName() + ". "
                + "Hence dropping the event." + e.getMessage(), e);
    }
}

From source file:org.athenasource.framework.unidbi.Datatypes.java

/**
 * Setting the parameter for the given prepared statement. This method will
 * cast the value to the object expected type (execept BOOLEAN) as
 * {@linkplain #getClass(int)}./*from w w w  .  ja v  a  2s .  c om*/
 * <p>INSERT, UPDATE should always call this method to set parameters before 'WHERE' keyword.</p>
 * <p><b>Warining</b>: For parameters after 'WHERE' keyword, always remember 'IS NULL' is not equal to '= NULL'.</p>
 *
 * @param index
 *            the parameter index
 * @param value
 *            the value for the parameter, can be <code>null</code>.
 * @param unidbType
 *            the datatype of the parameter
 * @throws SQLException
 *             in case of SQL problems or type conversion fails.
 */
public static void setParameter(PreparedStatement stmt, int index, Object value, int unidbType)
        throws SQLException {
    // Derby needs special handling.
    boolean isDerby = (stmt instanceof DelegatingPreparedStatement)
            ? ((DelegatingPreparedStatement) stmt).getDelegate().getClass().getName().contains("derby")
            : stmt.getClass().getName().contains("derby");
    if (value == null) {
        if (isDerby) {
            if (unidbType == NCHAR) {
                stmt.setNull(index, Datatypes.getSQLType(CHAR));
            } else if (unidbType == NVARCHAR) {
                stmt.setNull(index, Datatypes.getSQLType(VARCHAR));
            } else {
                stmt.setNull(index, Datatypes.getSQLType(unidbType));
            }
        } else {
            stmt.setNull(index, Datatypes.getSQLType(unidbType));
        }
    } else {
        try {
            switch (unidbType) {
            case BOOLEAN:
                stmt.setByte(index, (byte) (((Number) value).intValue() == 1 ? 1 : 0));
                break;
            case TINYINT:
                stmt.setByte(index, ((Number) value).byteValue());
                break;
            case SMALLINT:
                stmt.setShort(index, ((Number) value).shortValue());
                break;
            case INTEGER:
                stmt.setInt(index, ((Number) value).intValue());
                break;
            case BIGINT:
                stmt.setLong(index, ((Number) value).longValue());
                break;
            case DECIMAL:
                stmt.setBigDecimal(index, ((BigDecimal) value));
                break;
            case REAL:
                stmt.setFloat(index, ((Float) value).floatValue());
                break;
            case DOUBLE:
                stmt.setDouble(index, ((Double) value).doubleValue());
                break;
            case CHAR:
                stmt.setString(index, (String) value);
                break;
            case NCHAR:
                if (isDerby) {
                    stmt.setString(index, (String) value);
                } else {
                    stmt.setNString(index, (String) value);
                }
                break;
            case VARCHAR:
                stmt.setString(index, (String) value);
                break;
            case NVARCHAR:
                if (isDerby) {
                    stmt.setString(index, (String) value);
                } else {
                    stmt.setNString(index, (String) value);
                }
                break;
            case CLOB: // Clob/NClob can be represented as String without any problem. - Oct 16, 2008.
                stmt.setString(index, (String) value); // stmt.setClob(index, ((Clob) value));
                break;
            case NCLOB:
                if (isDerby) {
                    stmt.setString(index, (String) value);
                } else {
                    stmt.setNString(index, (String) value); // stmt.setNClob(index, ((NClob) value));
                }
                break;
            case BLOB:
                stmt.setBlob(index, ((Blob) value));
                break;
            case TIMESTAMP:
                stmt.setTimestamp(index, ((Timestamp) value));
                break;
            default:
                throw new IllegalArgumentException("[!NO SUCH UNIDB DATA TYPE: " + unidbType + "]");
            }
        } catch (ClassCastException cce) {
            throw new SQLException(
                    "Failed to convert " + value + " (" + value.getClass() + ") to " + getName(unidbType));
        }
    }
}

From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java

private PreparedStatement createPreapredStatementUsingSetXXX(String sql) throws SQLException {
    PreparedStatement ps = con.prepareStatement(sql);

    ps.setBoolean(1, true); //setBoolean
    ps.setBoolean(2, true); //setBoolean

    ps.setShort(3, Short.valueOf("1")); //setShort
    ps.setInt(4, 2); //setInt
    ps.setFloat(5, 3f); //setFloat
    ps.setDouble(6, Double.valueOf(4)); //setDouble
    ps.setString(7, "test'string\""); //setString
    ps.setLong(8, 5L); //setLong
    ps.setByte(9, (byte) 1); //setByte
    ps.setByte(10, (byte) 1); //setByte
    ps.setString(11, "2012-01-01"); //setString

    ps.setMaxRows(2);/*from w w w.ja va2s  .  c  om*/
    return ps;
}

From source file:org.jobjects.dao.annotation.ManagerTools.java

protected final void setAll(PreparedStatement pstmt, int i, Object obj) throws SQLException {
    if (obj instanceof Boolean) {
        pstmt.setBoolean(i, ((Boolean) obj).booleanValue());
    }//from   w ww .  jav a 2  s .c  o m
    if (obj instanceof Byte) {
        pstmt.setByte(i, ((Byte) obj).byteValue());
    }
    if (obj instanceof Short) {
        pstmt.setShort(i, ((Short) obj).shortValue());
    }
    if (obj instanceof Integer) {
        pstmt.setInt(i, ((Integer) obj).intValue());
    }
    if (obj instanceof Long) {
        pstmt.setLong(i, ((Long) obj).longValue());
    }
    if (obj instanceof Float) {
        pstmt.setFloat(i, ((Float) obj).floatValue());
    }
    if (obj instanceof Double) {
        pstmt.setDouble(i, ((Double) obj).doubleValue());
    }
    if (obj instanceof Timestamp) {
        pstmt.setTimestamp(i, ((Timestamp) obj));
    }
    if (obj instanceof Date) {
        pstmt.setDate(i, ((Date) obj));
    }
    if (obj instanceof BigDecimal) {
        pstmt.setBigDecimal(i, ((BigDecimal) obj));
    }
    if (obj instanceof String) {
        pstmt.setString(i, ((String) obj));
    }
}