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:com.sf.ddao.ops.InsertAndGetGeneratedKeySqlOperation.java

public boolean execute(Context context) throws Exception {
    try {/*from   w  w w  .  j a v a  2 s  .  c o  m*/
        final MethodCallCtx callCtx = CtxHelper.get(context, MethodCallCtx.class);
        PreparedStatement preparedStatement = statementFactory.createStatement(context, true);
        Object res = null;
        preparedStatement.executeUpdate();
        ResultSet resultSet = preparedStatement.getGeneratedKeys();
        if (resultSet.next()) {
            if (method.getReturnType() == Integer.TYPE || method.getReturnType() == Integer.class) {
                res = resultSet.getInt(1);
            } else if (method.getReturnType() == Long.TYPE || method.getReturnType() == Long.class) {
                res = resultSet.getLong(1);
            } else if (method.getReturnType() == BigDecimal.class) {
                res = resultSet.getBigDecimal(1);
            }
        }
        resultSet.close();
        preparedStatement.close();
        callCtx.setLastReturn(res);
        return CONTINUE_PROCESSING;
    } catch (Exception t) {
        throw new DaoException("Failed to execute sql operation for " + method, t);
    }
}

From source file:eu.databata.engine.dao.PropagationSqlLogRowMapper.java

@Override
public PropagationSqlLog mapRow(ResultSet rs, int rowNum) throws SQLException {
    PropagationSqlLog history = new PropagationSqlLog();
    history.setModuleName(rs.getString("module_name"));
    history.setDbChangeCode(rs.getString("db_change_code"));
    history.setSqlText(rs.getString("sql_text"));
    history.setRowsUpdated(rs.getLong("rows_updated"));
    history.setErrorCode(rs.getInt("error_code"));
    history.setErrorText(rs.getString("error_text"));
    history.setUpdateTime(rs.getTimestamp("update_time"));
    history.setExecutionTime(rs.getBigDecimal("execution_time"));
    return history;
}

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

public Holding getHolding(int holdingId) throws DAOException {
    Holding holding = null;// w w  w.j  a  v  a  2 s.c o m
    PreparedStatement selectHoldingStat = null;
    try {
        selectHoldingStat = sqlConnection.prepareStatement(SQL_SELECT_HOLDING);
        selectHoldingStat.setInt(1, holdingId);
        ResultSet rs = selectHoldingStat.executeQuery();
        if (rs.next()) {
            try {
                holding = new Holding(rs.getInt(1), rs.getDouble(2), rs.getBigDecimal(3),
                        StockTraderUtility.convertToCalendar(rs.getDate(4)), rs.getString(5), rs.getInt(6));
                return holding;

            } finally {
                try {
                    rs.close();
                } catch (Exception e) {
                    logger.debug("", e);
                }
            }
        }
    } catch (SQLException e) {
        throw new DAOException("An Exception is thrown during selecting a holding entry", e);
    } finally {
        if (selectHoldingStat != null) {
            try {
                selectHoldingStat.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }
    }
    return holding;
}

From source file:com.alibaba.otter.node.etl.common.db.utils.SqlUtils.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the specified value
 * type.// w ww .  j  av a 2 s  .  co  m
 * <p>
 * Uses the specifically typed ResultSet accessor methods, falling back to
 * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types.
 * <p>
 * Note that the returned value may not be assignable to the specified
 * required type, in case of an unknown type. Calling code needs to deal
 * with this case appropriately, e.g. throwing a corresponding exception.
 * 
 * @param rs is the ResultSet holding the data
 * @param index is the column index
 * @param requiredType the required value type (may be <code>null</code>)
 * @return the value object
 * @throws SQLException if thrown by the JDBC API
 */
private static String getResultSetValue(ResultSet rs, int index, Class<?> requiredType) throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value = null;
    boolean wasNullCheck = false;

    // Explicitly extract typed value, as far as possible.
    if (String.class.equals(requiredType)) {
        value = rs.getString(index);
    } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) {
        value = Boolean.valueOf(rs.getBoolean(index));
        wasNullCheck = true;
    } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) {
        value = new Byte(rs.getByte(index));
        wasNullCheck = true;
    } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) {
        value = new Short(rs.getShort(index));
        wasNullCheck = true;
    } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) {
        value = new Long(rs.getLong(index));
        wasNullCheck = true;
    } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
        wasNullCheck = true;
    } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) {
        value = new Float(rs.getFloat(index));
        wasNullCheck = true;
    } else if (double.class.equals(requiredType) || Double.class.equals(requiredType)
            || Number.class.equals(requiredType)) {
        value = new Double(rs.getDouble(index));
        wasNullCheck = true;
    } else if (java.sql.Time.class.equals(requiredType)) {
        // try {
        // value = rs.getTime(index);
        // } catch (SQLException e) {
        value = rs.getString(index);// ?string0000Time
        // if (value == null && !rs.wasNull()) {
        // value = "00:00:00"; //
        // mysqlzeroDateTimeBehavior=convertToNull0null
        // }
        // }
    } else if (java.sql.Timestamp.class.equals(requiredType) || java.sql.Date.class.equals(requiredType)) {
        // try {
        // value = convertTimestamp(rs.getTimestamp(index));
        // } catch (SQLException e) {
        // ?string0000-00-00 00:00:00Timestamp 
        value = rs.getString(index);
        // if (value == null && !rs.wasNull()) {
        // value = "0000:00:00 00:00:00"; //
        // mysqlzeroDateTimeBehavior=convertToNull0null
        // }
        // }
    } else if (BigDecimal.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (BigInteger.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (Blob.class.equals(requiredType)) {
        value = rs.getBlob(index);
    } else if (Clob.class.equals(requiredType)) {
        value = rs.getClob(index);
    } else if (byte[].class.equals(requiredType)) {
        try {
            byte[] bytes = rs.getBytes(index);
            if (bytes == null) {
                value = null;
            } else {
                value = new String(bytes, "ISO-8859-1");// binaryiso-8859-1
            }
        } catch (UnsupportedEncodingException e) {
            throw new SQLException(e);
        }
    } else {
        // Some unknown type desired -> rely on getObject.
        value = getResultSetValue(rs, index);
    }

    // Perform was-null check if demanded (for results that the
    // JDBC driver returns as primitives).
    if (wasNullCheck && (value != null) && rs.wasNull()) {
        value = null;
    }

    return (value == null) ? null : convertUtilsBean.convert(value);
}

From source file:com.splicemachine.derby.impl.sql.execute.operations.InsertOperationIT.java

@Test
public void testInsertOverMergeSortOuterJoinIsCorrect() throws Exception {
    /*// w  w w . j  a  v  a 2 s. c  o m
     * Regression test for DB-1833. Tests that we can insert over a subselect that has a merge-sort
     * join present,without getting any errors.
     */
    long insertCount = methodWatcher.executeUpdate(String.format("insert into %1$s select "
            + "%2$s.a,%3$s.c,%2$s.b,%3$s.d " + "from %2$s --SPLICE-PROPERTIES joinStrategy=SORTMERGE \n"
            + "right join %3$s on %2$s.a=%3$s.c", "T5", "T3", "T4"));
    Assert.assertEquals("Incorrect number of rows inserted!", 2, insertCount);
    ResultSet rs = methodWatcher.executeQuery("select * from T5");
    int count = 0;
    while (rs.next()) {
        int a = rs.getInt(1);
        if (rs.wasNull()) {
            BigDecimal b = rs.getBigDecimal(3);
            Assert.assertTrue("B is not null!", rs.wasNull());
        } else {
            BigDecimal b = rs.getBigDecimal(3);
            Assert.assertFalse("B is null!", rs.wasNull());
            Assert.assertTrue("Incorrect B value!",
                    BigDecimal.ONE.subtract(b).abs().compareTo(new BigDecimal(".0000000001")) < 0);
        }
        count++;
        int c = rs.getInt(2);
        Assert.assertFalse("C is null!", rs.wasNull());
        int d = rs.getInt(4);
        Assert.assertFalse("D is null!", rs.wasNull());
    }
    Assert.assertEquals("Incorrect row count!", 2, count);
}

From source file:com.streamsets.pipeline.stage.it.DecimalTypeIT.java

@Test
public void zeroScale() throws Exception {
    executeUpdate("CREATE TABLE `tbl` (id int, dec decimal(2, 0)) PARTITIONED BY (dt string) STORED AS AVRO");

    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().decimalConfig(2, 0).build();
    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();

    List<Record> records = new LinkedList<>();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 1));
    map.put("dec", Field.create(BigDecimal.valueOf(12)));
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);/*  www .j a v  a2  s . c o m*/

    processRecords(processor, hiveTarget, records);

    assertQueryResult("select * from tbl order by id", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("tbl.id", Types.INTEGER),
                    new ImmutablePair("tbl.dec", Types.DECIMAL), new ImmutablePair("tbl.dt", Types.VARCHAR));

            Assert.assertTrue("Table tbl doesn't contain any rows", rs.next());
            Assert.assertEquals(1, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(12), rs.getBigDecimal(2));

            Assert.assertFalse("Unexpected number of rows", rs.next());
        }
    });
}

From source file:com.google.enterprise.connector.salesforce.storetype.DBStore.java

public void setDocList(String checkpoint, String str_store_entry) {

    DatabaseMetaData dbm = null;/*from   ww  w .  j ava  2s  .c  o  m*/
    Connection connection = null;

    logger.log(Level.FINEST, "Setting doclist " + checkpoint);
    logger.log(Level.FINEST, "Setting store_entry " + str_store_entry);
    try {

        connection = ds.getConnection();
        connection.setAutoCommit(true);

        dbm = connection.getMetaData();

        //logger.log(Level.FINE,"Base64 ENCODING...");
        String encode_entry = new String(
                org.apache.commons.codec.binary.Base64.encodeBase64(str_store_entry.getBytes()));
        str_store_entry = encode_entry;

        //logger.log(Level.FINE,"Setting store_entry ENCODED " + str_store_entry);

        if (dbm.getDatabaseProductName().equals("MySQL")) {
            //get the most recent row
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            String update_stmt = "select crawl_set from " + this.instance_table
                    + " where crawl_set=(select max(crawl_set) from " + this.instance_table + ")";
            logger.log(Level.FINE, "Getting lastentryp in db: " + update_stmt);
            ResultSet rs = statement.executeQuery(update_stmt);

            boolean ret_rows = rs.first();

            String last_entry_in_db = null;

            while (ret_rows) {
                BigDecimal crawl_set = rs.getBigDecimal("crawl_set");
                last_entry_in_db = crawl_set.toPlainString();
                ret_rows = rs.next();
            }

            logger.log(Level.FINER, "Last_Entry_in_Database " + last_entry_in_db);

            if (last_entry_in_db != null) {
                if (last_entry_in_db.startsWith(checkpoint)) {
                    //increment if in the same set
                    BigDecimal bd = new BigDecimal(last_entry_in_db);
                    bd = bd.add(new BigDecimal(".00001"));
                    logger.log(Level.INFO, "Adding to DBStore. Index Value: " + bd.toPlainString());
                    update_stmt = "insert into " + this.instance_table
                            + " (crawl_set,crawl_data) values (?,COMPRESS(?))";

                    PreparedStatement ps = connection.prepareStatement(update_stmt);
                    ps.setString(1, bd.toPlainString());
                    ps.setString(2, str_store_entry);
                    ps.executeUpdate();
                    ps.close();
                } else {
                    //otherwise add the the 0th row for this set
                    logger.log(Level.INFO, "Adding to DBStore. Index Value: " + checkpoint + ".00000");
                    update_stmt = "insert into " + this.instance_table
                            + " (crawl_set,crawl_data) values (?,COMPRESS(?))";
                    PreparedStatement ps = connection.prepareStatement(update_stmt);
                    ps.setString(1, checkpoint + ".00000");
                    ps.setString(2, str_store_entry);
                    ps.executeUpdate();
                    ps.close();
                }
            } else {
                logger.log(Level.INFO, "Adding to DBStore. Index Value: " + checkpoint + ".00000");
                update_stmt = "insert into " + this.instance_table
                        + " (crawl_set,crawl_data) values (?,COMPRESS(?))";
                PreparedStatement ps = connection.prepareStatement(update_stmt);
                ps.setString(1, checkpoint + ".00000");
                ps.setString(2, str_store_entry);
                ps.executeUpdate();
                ps.close();

            }

            rs.close();
            statement.close();
            connection.close();
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception initializing context Datasource " + ex);
        return;
    }
}

From source file:net.sourceforge.squirrel_sql.fw.datasetviewer.cellcomponent.DataTypeBigDecimal.java

/**
 * On input from the DB, read the data from the ResultSet into the appropriate
 * type of object to be stored in the table cell.
 *///from w w  w  .  j  a v a 2s  . com
public Object readResultSet(ResultSet rs, int index, boolean limitDataRead) throws java.sql.SQLException {

    BigDecimal data = rs.getBigDecimal(index);
    if (rs.wasNull())
        return null;
    else
        return data;
}

From source file:org.ojbc.adapters.analyticaldatastore.dao.IncidentRowMapper.java

@Override
public Incident mapRow(ResultSet rs, int rowNum) throws SQLException {
    Incident incident = new Incident();

    incident.setIncidentCaseNumber(rs.getString("IncidentCaseNumber"));
    incident.setIncidentDate(rs.getDate("IncidentDate"));
    incident.setIncidentID(rs.getInt("IncidentID"));
    incident.setIncidentLocationStreetAddress(rs.getString("IncidentLocationStreetAddress"));
    incident.setIncidentLocationTown(rs.getString("IncidentLocationTown"));
    incident.setIncidentTime(rs.getTime("IncidentTime"));
    incident.setReportingAgencyID(rs.getInt("ReportingAgencyID"));
    incident.setIncidentLocationLatitude(rs.getBigDecimal("IncidentLocationLatitude"));
    incident.setIncidentLocationLongitude(rs.getBigDecimal("IncidentLocationLongitude"));
    incident.setReportingSystem(rs.getString("ReportingSystem"));

    String recordType = rs.getString("RecordType");

    if (StringUtils.isNotBlank(recordType)) {
        incident.setRecordType(recordType.charAt(0));
    }//  ww w . j  a  v a2  s . c  om

    return incident;
}

From source file:com.streamsets.pipeline.stage.it.DecimalTypeIT.java

@Test
public void correctCases() throws Exception {
    executeUpdate("CREATE TABLE `tbl` (id int, dec decimal(4, 2)) PARTITIONED BY (dt string) STORED AS AVRO");

    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().decimalConfig(4, 2).build();
    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();

    List<Record> records = new LinkedList<>();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 1));
    map.put("dec", Field.create(BigDecimal.valueOf(12.12)));
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);//w w w  .  jav a  2 s.  c  o m

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 2));
    map.put("dec", Field.create(BigDecimal.valueOf(1.0)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 3));
    map.put("dec", Field.create(BigDecimal.valueOf(12.0)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 4));
    map.put("dec", Field.create(BigDecimal.valueOf(0.1)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 5));
    map.put("dec", Field.create(BigDecimal.valueOf(0.12)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    processRecords(processor, hiveTarget, records);

    assertQueryResult("select * from tbl order by id", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("tbl.id", Types.INTEGER),
                    new ImmutablePair("tbl.dec", Types.DECIMAL), new ImmutablePair("tbl.dt", Types.VARCHAR));

            Assert.assertTrue("Table tbl doesn't contain any rows", rs.next());
            Assert.assertEquals(1, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(12.12), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(2, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(1), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(3, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(12), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(4, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(0.1), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(5, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(0.12), rs.getBigDecimal(2));

            Assert.assertFalse("Unexpected number of rows", rs.next());
        }
    });
}