Example usage for java.sql ResultSet getBigDecimal

List of usage examples for java.sql ResultSet getBigDecimal

Introduction

In this page you can find the example usage for java.sql ResultSet getBigDecimal.

Prototype

BigDecimal getBigDecimal(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a java.math.BigDecimal with full precision.

Usage

From source file:nl.tudelft.stocktrader.derby.DerbyCustomerDAO.java

public Account getCustomerByUserId(String userId) throws DAOException {
    PreparedStatement getCustomerByUserId = null;

    try {/*from w  w w.  j av a2  s .c  o m*/
        getCustomerByUserId = sqlConnection.prepareStatement(SQL_SELECT_GET_CUSTOMER_BY_USERID);
        getCustomerByUserId.setString(1, userId);
        ResultSet rs = getCustomerByUserId.executeQuery();
        if (rs.next()) {
            try {
                Account bean = new Account(rs.getInt(1), rs.getString(2),
                        StockTraderUtility.convertToCalendar(rs.getDate(3)), rs.getBigDecimal(4), rs.getInt(5),
                        rs.getBigDecimal(6), StockTraderUtility.convertToCalendar(rs.getDate(7)), rs.getInt(8),
                        rs.getString(9));
                return bean;
            } finally {
                try {
                    rs.close();
                } catch (SQLException e) {
                    logger.debug("", e);
                }
            }
        }
    } catch (SQLException e) {
        throw new DAOException("", e);
    } finally {
        if (getCustomerByUserId != null) {
            try {
                getCustomerByUserId.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }
    }
    return null;
}

From source file:org.castor.cpa.persistence.sql.keygen.AbstractAfterKeyGenerator.java

/**
 * {@inheritDoc}/*from www. j a  v a  2s .  com*/
 */
public final Object executeStatement(final Database database, final CastorConnection conn,
        final Identity identity, final ProposedEntity entity) throws PersistenceException {
    Identity internalIdentity = identity;

    CastorStatement stmt = conn.createStatement();
    try {
        if ((internalIdentity == null) && _useJDBC30) {
            Field field = Statement.class.getField("RETURN_GENERATED_KEYS");

            stmt.prepareStatement(_insert);
            String statement = stmt.toString();
            Integer rgk = (Integer) field.get(statement);

            Class[] types = new Class[] { String.class, int.class };
            Object[] args = new Object[] { statement, rgk };
            Method method = Connection.class.getMethod("prepareStatement", types);

            stmt.setStatement((PreparedStatement) method.invoke(conn.getConnection(), args));
        } else {
            stmt.prepareStatement(_insert);
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace(Messages.format("jdo.creating", _engineType, stmt.toString()));
        }

        bindFields(entity, stmt);

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.format("jdo.creating", _engineType, stmt.toString()));
        }

        stmt.executeUpdate();

        SQLColumnInfo[] ids = _engine.getColumnInfoForIdentities();

        if (internalIdentity == null) {
            if (_useJDBC30) {
                // use key returned by INSERT statement.
                Class cls = PreparedStatement.class;
                Method method = cls.getMethod("getGeneratedKeys", (Class[]) null);

                ResultSet keySet = (ResultSet) method.invoke(stmt.getStatement(), (Object[]) null);

                int i = 1;
                int sqlType;
                List<Object> keys = new ArrayList<Object>();
                while (keySet.next()) {
                    sqlType = ids[i - 1].getSqlType();
                    Object temp;
                    if (sqlType == java.sql.Types.INTEGER) {
                        temp = new Integer(keySet.getInt(i));
                    } else if (sqlType == java.sql.Types.NUMERIC) {
                        temp = keySet.getBigDecimal(i);
                    } else {
                        temp = keySet.getObject(i);
                    }

                    keys.add(ids[i - 1].toJava(temp));
                    i++;
                }
                internalIdentity = new Identity(keys.toArray());
            } else {
                // generate key after INSERT.
                internalIdentity = generateKey(database, conn);
            }
        }

        return internalIdentity;
    } catch (SQLException except) {
        LOG.fatal(Messages.format("jdo.storeFatal", _engineType, stmt.toString()), except);
        throw new PersistenceException(Messages.format("persist.nested", except), except);
    } catch (NoSuchMethodException ex) {
        throw new CastorIllegalStateException(ex);
    } catch (NoSuchFieldException ex) {
        throw new CastorIllegalStateException(ex);
    } catch (IllegalAccessException ex) {
        throw new CastorIllegalStateException(ex);
    } catch (InvocationTargetException ex) {
        throw new CastorIllegalStateException(ex);
    } finally {
        //close statement
        try {
            stmt.close();
        } catch (SQLException e) {
            LOG.warn("Problem closing JDBC statement", e);
        }
    }
}

From source file:org.apache.phoenix.end2end.SortOrderIT.java

@Test
public void decimalRangeDescPK1() throws Exception {
    String ddl = "CREATE TABLE " + TABLE + " (oid DECIMAL PRIMARY KEY DESC)";
    Connection conn = DriverManager.getConnection(getUrl());
    conn.createStatement().execute(ddl);
    conn.createStatement().execute("UPSERT INTO " + TABLE + " VALUES(4.99)");
    conn.createStatement().execute("UPSERT INTO " + TABLE + " VALUES(4.0)");
    conn.createStatement().execute("UPSERT INTO " + TABLE + " VALUES(5.0)");
    conn.createStatement().execute("UPSERT INTO " + TABLE + " VALUES(5.001)");
    conn.createStatement().execute("UPSERT INTO " + TABLE + " VALUES(5.999)");
    conn.createStatement().execute("UPSERT INTO " + TABLE + " VALUES(6.0)");
    conn.createStatement().execute("UPSERT INTO " + TABLE + " VALUES(6.001)");
    conn.commit();/*w  w w .  j a  va2  s . co m*/

    String query = "SELECT * FROM " + TABLE + " WHERE oid >= 5.0 AND oid < 6.0";
    ResultSet rs = conn.createStatement().executeQuery(query);
    assertTrue(rs.next());
    assertTrue(new BigDecimal("5.999").compareTo(rs.getBigDecimal(1)) == 0);
    assertTrue(rs.next());
    assertTrue(new BigDecimal("5.001").compareTo(rs.getBigDecimal(1)) == 0);
    assertTrue(rs.next());
    assertTrue(new BigDecimal("5.0").compareTo(rs.getBigDecimal(1)) == 0);
    assertFalse(rs.next());
}

From source file:org.mayocat.shop.catalog.store.jdbi.mapper.ProductMapper.java

@Override
public Product map(int index, ResultSet resultSet, StatementContext statementContext) throws SQLException {
    try {/*  ww w  .  j av a 2s. com*/
        Product product = new Product((UUID) resultSet.getObject("id"));
        product.setTenantId((UUID) resultSet.getObject("tenant_id"));
        if (resultSet.getObject("parent_id") != null) {
            product.setParentId((UUID) resultSet.getObject("parent_id"));
        }
        product.setSlug(resultSet.getString("slug"));
        product.setTitle(resultSet.getString("title"));
        product.setDescription(resultSet.getString("description"));
        product.setCreationDate(resultSet.getTimestamp("creation_date"));
        if (resultSet.getObject("on_shelf") != null) {
            product.setOnShelf(resultSet.getBoolean("on_shelf"));
        }
        product.setPrice(resultSet.getBigDecimal("price"));

        if (!Strings.isNullOrEmpty(resultSet.getString("taxes"))) {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, String> taxes = mapper.readValue(resultSet.getString("taxes"),
                    new TypeReference<Map<String, String>>() {
                    });
            if (taxes.containsKey("vat")) {
                product.setVatRateId(taxes.get("vat"));
            }
        }

        product.setWeight(resultSet.getBigDecimal("weight"));
        if (resultSet.getObject("stock") != null) {
            product.setStock(resultSet.getInt("stock"));
        }
        product.setVirtual(resultSet.getBoolean("virtual"));
        UUID featuredImageId = (UUID) resultSet.getObject("featured_image_id");
        if (featuredImageId != null) {
            product.setFeaturedImageId(featuredImageId);
        }

        if (MapperUtils.hasColumn("localization_data", resultSet)
                && !Strings.isNullOrEmpty(resultSet.getString("localization_data"))) {
            ObjectMapper mapper = new ObjectMapper();
            Map<Locale, Map<String, Object>> localizedVersions = Maps.newHashMap();
            Map[] data = mapper.readValue(resultSet.getString("localization_data"), Map[].class);
            for (Map map : data) {

                localizedVersions.put(Locale.forLanguageTag((String) map.get("locale")),
                        (Map) map.get("entity"));
            }
            product.setLocalizedVersions(localizedVersions);
        }

        String model = resultSet.getString("model");
        if (!Strings.isNullOrEmpty(model)) {
            product.setModel(model);
        }
        String type = resultSet.getString("product_type");
        if (!Strings.isNullOrEmpty(type)) {
            product.setType(type);
        }

        if (resultSet.getArray("features") != null) {
            // There's no support for getting the pg uuid array as a Java UUID array (or even String array) at the time
            // this is written, we have to iterate over the array own result set and construct the Java array ourselves
            List<UUID> ids = new ArrayList<>();
            Array array = resultSet.getArray("features");
            if (array != null) {
                ResultSet featuresResultSet = array.getResultSet();
                while (featuresResultSet.next()) {
                    ids.add((UUID) featuresResultSet.getObject("value"));
                }
                product.setFeatures(ids);
            }
        }

        return product;
    } catch (IOException e) {
        throw new SQLException("Failed to de-serialize JSON data", e);
    }
}

From source file:me.j360.idgen.impl.test.TableIdGenServiceJdbcTest.java

/**
 * get next BigDecimal id using query directly.
 * /* w  w  w . j  a  v a2  s. c  om*/
 * @param tableName
 *            table name
 * @return next BigDecimal Id
 */
private BigDecimal peekNextBigDecimalId(String tableName) {
    try {
        DataSource dataSource = (DataSource) applicationContext.getBean("util_datasource");
        Connection conn = dataSource.getConnection();
        try {
            Statement statement = conn.createStatement();

            ResultSet rs = statement
                    .executeQuery("SELECT next_id FROM idstest " + "WHERE table_name = '" + tableName + "'");
            if (rs.next()) {
                return rs.getBigDecimal(1);
            } else {
                fail(tableName + " row not in ids table.");
                return null; // for compiler
            }
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        System.err.println("Unable to peek next_id." + e);
        fail("Unable to peek next_id. " + e);
        return null; // for compiler
    }
}

From source file:me.j360.idgen.impl.test.TableIdGenServiceJdbcTest.java

/**
 * Tests to see whether or not the current DataSource supports BigDecimal
 * //from   w ww. jav a  2 s .c o  m
 * @return boolean check bigcimal implemented
 */
private boolean isBigDecimalImplemented() {
    String tableName = "foorbar_table";

    // Add a row that can be selected.
    initializeNextLongId(tableName, 1);

    try {
        DataSource dataSource = (DataSource) applicationContext.getBean("util_datasource");
        Connection conn = dataSource.getConnection();
        try {
            Statement statement = conn.createStatement();

            ResultSet rs = statement
                    .executeQuery("SELECT next_id FROM idstest " + "WHERE table_name = '" + tableName + "'");
            if (rs.next()) {
                rs.getBigDecimal(1);
            } else {
                fail(tableName + " row not in ids table.");
                return false; // for compiler
            }
        } finally {
            conn.close();
        }

        // Implemented
        return true;
    } catch (Exception e) {
        if (e.toString().toLowerCase().indexOf("implemented") > 0) {
            // Not implemented
            return false;
        }
        System.err.println("Unable to test for BigDecimal support." + e);
        fail("Unable to test for BigDecimal support. " + e);
        return false; // for compiler
    }
}

From source file:nl.tudelft.stocktrader.mysql.MySQLCustomerDAO.java

public Account login(String userId, String password) throws DAOException {
    PreparedStatement selectCustomerProfileByUserId = null;
    PreparedStatement updateCustomerLogin = null;
    PreparedStatement selectCustomerLogin = null;
    try {/*  ww w .  j  a va2  s.  c o  m*/
        selectCustomerProfileByUserId = sqlConnection.prepareStatement(SQL_SELECT_CUSTOMER_PROFILE_BY_USERID);
        selectCustomerProfileByUserId.setString(1, userId);
        ResultSet customerProfileRS = selectCustomerProfileByUserId.executeQuery();
        if (customerProfileRS.next()) {
            try {
                String userPassword = customerProfileRS.getString(2);
                if (userPassword.equals(password)) {
                    try {
                        updateCustomerLogin = sqlConnection.prepareStatement(SQL_UPDATE_CUSTOMER_LOGIN);
                        updateCustomerLogin.setString(1, userId);
                        updateCustomerLogin.executeUpdate();
                        selectCustomerLogin = sqlConnection.prepareStatement(SQL_SELECT_CUSTOMER_LOGIN);
                        selectCustomerLogin.setString(1, userId);
                        ResultSet rs = selectCustomerLogin.executeQuery();
                        if (rs.next()) {
                            try {
                                Account accountData = new Account(rs.getInt(1), userId,
                                        StockTraderUtility.convertToCalendar(rs.getDate(2)),
                                        rs.getBigDecimal(3), rs.getInt(4), rs.getBigDecimal(5),
                                        StockTraderUtility.convertToCalendar(rs.getDate(6)), rs.getInt(7) + 1);
                                return accountData;
                            } finally {
                                try {
                                    rs.close();
                                } catch (SQLException e) {
                                    logger.debug("", e);
                                }
                            }
                        }
                    } catch (SQLException e) {
                        throw new DAOException("", e);
                    } finally {
                        if (updateCustomerLogin != null) {
                            try {
                                updateCustomerLogin.close();
                            } catch (SQLException e) {
                                logger.debug("", e);
                            }
                        }
                        if (selectCustomerLogin != null) {
                            try {
                                selectCustomerLogin.close();
                            } catch (SQLException e) {
                                logger.debug("", e);
                            }
                        }
                    }
                }
            } finally {
                try {
                    customerProfileRS.close();
                } catch (SQLException e) {
                    logger.debug("", e);
                }
            }
        }

    } catch (SQLException e) {
        throw new DAOException("", e);
    } finally {
        if (selectCustomerProfileByUserId != null) {
            try {
                selectCustomerProfileByUserId.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }
    }
    return null;
}

From source file:org.mayocat.shop.shipping.store.jdbi.mapper.CarrierMapper.java

@Override
public Carrier map(int index, ResultSet r, StatementContext ctx) throws SQLException {
    Carrier carrier = null;//from   w w  w  .j  av  a 2 s.  c om
    UUID thisRowId = (UUID) r.getObject("id");
    if (ctx.getAttribute("__accumulator") != null) {
        carrier = (Carrier) ctx.getAttribute("__accumulator");
        if (!carrier.getId().equals(thisRowId)) {
            carrier = new Carrier();
        }
    }
    if (carrier == null) {
        carrier = new Carrier();
    }
    carrier.setId(thisRowId);
    carrier.setTitle(r.getString("title"));
    carrier.setDescription(r.getString("description"));
    carrier.setId((UUID) r.getObject("id"));
    carrier.setTenantId((UUID) r.getObject("tenant_id"));
    carrier.setMinimumDays(r.getInt("minimum_days"));
    carrier.setMaximumDays(r.getInt("maximum_days"));
    carrier.setStrategy(Strategy.fromJson(r.getString("strategy")));
    carrier.setPerShipping(r.getBigDecimal("per_shipping"));
    carrier.setPerItem(r.getBigDecimal("per_item"));
    carrier.setPerAdditionalUnit(r.getBigDecimal("per_additional_unit"));

    ObjectMapper objectMapper = new ObjectMapper();
    try {
        carrier.setDestinations(objectMapper.<List<String>>readValue(r.getString("destinations"),
                new TypeReference<List<String>>() {
                }));
    } catch (IOException e) {
        throw new SQLException("Failed to de-serialize carrier destinations", e);
    }

    if (r.getBigDecimal("price") != null) {
        CarrierRule rule = new CarrierRule();
        rule.setUpToValue(r.getBigDecimal("up_to_value"));
        rule.setPrice(r.getBigDecimal("price"));
        carrier.addRule(rule);
    }

    if (r.getBigDecimal("vat_rate") != null) {
        carrier.setVatRate(r.getBigDecimal("vat_rate"));
    }

    ctx.setAttribute("__accumulator", carrier);
    return carrier;
}

From source file:com.cloudera.sqoop.tool.ImportTool.java

/**
 * Return the max value in the incremental-import test column. This
 * value must be numeric.//from ww  w.j a  v  a2 s . com
 */
private BigDecimal getMaxColumnId(SqoopOptions options) throws SQLException {
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT MAX(");
    sb.append(options.getIncrementalTestColumn());
    sb.append(") FROM ");
    sb.append(options.getTableName());

    String where = options.getWhereClause();
    if (null != where) {
        sb.append(" WHERE ");
        sb.append(where);
    }

    Connection conn = manager.getConnection();
    Statement s = null;
    ResultSet rs = null;
    try {
        s = conn.createStatement();
        rs = s.executeQuery(sb.toString());
        if (!rs.next()) {
            // This probably means the table is empty.
            LOG.warn("Unexpected: empty results for max value query?");
            return null;
        }

        return rs.getBigDecimal(1);
    } finally {
        try {
            if (null != rs) {
                rs.close();
            }
        } catch (SQLException sqlE) {
            LOG.warn("SQL Exception closing resultset: " + sqlE);
        }

        try {
            if (null != s) {
                s.close();
            }
        } catch (SQLException sqlE) {
            LOG.warn("SQL Exception closing statement: " + sqlE);
        }
    }
}

From source file:org.nuclos.server.dblayer.impl.standard.StandardSqlDBAccess.java

protected static <T> T getResultSetValue(ResultSet rs, int index, Class<T> javaType) throws SQLException {
    Object value;//from www.  j  a  v a 2s.  c  o m
    if (javaType == String.class) {
        value = rs.getString(index);
    } else if (javaType == NuclosPassword.class) {
        value = new NuclosPassword(ServerCryptUtil.decrypt(rs.getString(index)));
    } else if (javaType == Double.class) {
        value = rs.getDouble(index);
    } else if (javaType == Long.class) {
        value = rs.getLong(index);
    } else if (javaType == Integer.class) {
        value = rs.getInt(index);
    } else if (javaType == Boolean.class) {
        value = rs.getBoolean(index);
    } else if (javaType == BigDecimal.class) {
        value = rs.getBigDecimal(index);
    } else if (javaType == java.util.Date.class || javaType == java.sql.Date.class) {
        value = rs.getDate(index);
    } else if (javaType == InternalTimestamp.class) {
        value = InternalTimestamp.toInternalTimestamp(rs.getTimestamp(index));
    } else if (javaType == NuclosDateTime.class) {
        value = NuclosDateTime.toNuclosDateTime(rs.getTimestamp(index));
    } else if (javaType == byte[].class) {
        value = rs.getBytes(index);
    } else if (javaType == Object.class) {
        value = rs.getObject(index);
    } else if (javaType == NuclosScript.class) {
        String xml = rs.getString(index);
        if (StringUtils.isNullOrEmpty(xml)) {
            value = null;
        } else {
            final XStreamSupport xs = XStreamSupport.getInstance();
            final XStream xstream = xs.getXStream();
            try {
                value = xstream.fromXML(rs.getString(index));
            } finally {
                xs.returnXStream(xstream);
            }
        }
    } else {
        throw new IllegalArgumentException("Class " + javaType + " not supported by readField");
    }
    return rs.wasNull() ? null : javaType.cast(value);
}