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:org.kuali.kfs.gl.batch.dataaccess.impl.LedgerPreparedStatementCachingDaoJdbc.java

public ExpenditureTransaction getExpenditureTransaction(final Transaction t) {
    return new RetrievingJdbcWrapper<ExpenditureTransaction>() {
        @Override/*w w w.  j  av a 2  s.c om*/
        protected void populateStatement(PreparedStatement preparedStatement) throws SQLException {
            preparedStatement.setInt(1, t.getUniversityFiscalYear());
            preparedStatement.setString(2, t.getChartOfAccountsCode());
            preparedStatement.setString(3, t.getAccountNumber());
            preparedStatement.setString(4, t.getSubAccountNumber());
            preparedStatement.setString(5, t.getFinancialObjectCode());
            preparedStatement.setString(6, t.getFinancialSubObjectCode());
            preparedStatement.setString(7, t.getFinancialBalanceTypeCode());
            preparedStatement.setString(8, t.getFinancialObjectTypeCode());
            preparedStatement.setString(9, t.getUniversityFiscalPeriodCode());
            preparedStatement.setString(10, t.getProjectCode());
            preparedStatement.setString(11,
                    StringUtils.isBlank(t.getOrganizationReferenceId())
                            ? GeneralLedgerConstants.getDashOrganizationReferenceId()
                            : t.getOrganizationReferenceId());
        }

        @Override
        protected ExpenditureTransaction extractResult(ResultSet resultSet) throws SQLException {
            ExpenditureTransaction expenditureTransaction = new ExpenditureTransaction();
            expenditureTransaction.setUniversityFiscalYear(t.getUniversityFiscalYear());
            expenditureTransaction.setChartOfAccountsCode(t.getChartOfAccountsCode());
            expenditureTransaction.setAccountNumber(t.getAccountNumber());
            expenditureTransaction.setSubAccountNumber(t.getSubAccountNumber());
            expenditureTransaction.setObjectCode(t.getFinancialObjectCode());
            expenditureTransaction.setSubObjectCode(t.getFinancialSubObjectCode());
            expenditureTransaction.setBalanceTypeCode(t.getFinancialBalanceTypeCode());
            expenditureTransaction.setObjectTypeCode(t.getFinancialObjectTypeCode());
            expenditureTransaction.setUniversityFiscalAccountingPeriod(t.getUniversityFiscalPeriodCode());
            expenditureTransaction.setProjectCode(t.getProjectCode());
            expenditureTransaction
                    .setOrganizationReferenceId(StringUtils.isBlank(t.getOrganizationReferenceId())
                            ? GeneralLedgerConstants.getDashOrganizationReferenceId()
                            : t.getOrganizationReferenceId());
            expenditureTransaction
                    .setAccountObjectDirectCostAmount(new KualiDecimal(resultSet.getBigDecimal(1)));
            return expenditureTransaction;
        }
    }.get(ExpenditureTransaction.class);
}

From source file:com.nextep.designer.sqlgen.mysql.impl.MySqlCapturer.java

/**
 * Builds the columns map of the given table. This table will be filled with
 * the new fetched columns./*from ww w  .  ja  v  a2s.  c o  m*/
 * 
 * @param conn
 *            Connection to fetch columns
 * @param md
 *            pre-computed {@link DatabaseMetaData}
 * @param context
 *            the current {@link ICaptureContext}
 * @param monitor
 *            the {@link IProgressMonitor} to report progress to
 * @param table
 *            the table to fetch columns for
 * @return a map of {@link IBasicColumn} hashed by their qualified column
 *         name
 * @throws SQLException
 */
private Map<String, IBasicColumn> buildColumnsMap(Connection conn, DatabaseMetaData md, ICaptureContext context,
        IProgressMonitor monitor, Map<String, IBasicTable> tablesMap) throws SQLException {
    final IMySqlModelService mysqlModelService = CorePlugin.getService(IMySqlModelService.class);
    final IDatatypeProvider datatypeProvider = DBGMHelper.getDatatypeProvider(DBVendor.MYSQL);
    final Map<String, IBasicColumn> columnsMap = new HashMap<String, IBasicColumn>();
    PreparedStatement stmt = null;
    ResultSet rset = null;
    try {
        stmt = conn.prepareStatement(
                "select TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, IS_NULLABLE, EXTRA, COLUMN_DEFAULT, CHARACTER_SET_NAME, COLLATION_NAME, COLUMN_TYPE, COLUMN_COMMENT "
                        + " from information_schema.columns where table_schema=?");
        stmt.setString(1, context.getSchema());

        rset = stmt.executeQuery();
        while (rset.next()) {
            monitor.worked(1);
            final String tableName = rset.getString("TABLE_NAME"); //$NON-NLS-1$
            final IMySQLTable table = (IMySQLTable) tablesMap.get(tableName);
            if (table == null) {
                continue;
            }
            final String columnName = rset.getString("COLUMN_NAME"); //$NON-NLS-1$
            final int rank = rset.getInt("ORDINAL_POSITION"); //$NON-NLS-1$
            String datatype = rset.getString("DATA_TYPE").toUpperCase(); //$NON-NLS-1$
            int numericLength = rset.getInt("NUMERIC_PRECISION"); //$NON-NLS-1$
            int dataPrecision = rset.getInt("NUMERIC_SCALE"); //$NON-NLS-1$
            BigDecimal dataCharLength = rset.getBigDecimal("CHARACTER_MAXIMUM_LENGTH"); //$NON-NLS-1$
            final boolean nullable = "YES".equals(rset.getString("IS_NULLABLE")); //$NON-NLS-1$ //$NON-NLS-2$
            final boolean autoInc = "auto_increment".equals(rset.getString("EXTRA")); //$NON-NLS-1$ //$NON-NLS-2$
            String dataDefault = rset.getString("COLUMN_DEFAULT"); //$NON-NLS-1$

            final String charset = rset.getString("CHARACTER_SET_NAME"); //$NON-NLS-1$
            final String collation = rset.getString("COLLATION_NAME"); //$NON-NLS-1$
            final String columnType = rset.getString("COLUMN_TYPE"); //$NON-NLS-1$
            final String colComments = rset.getString("COLUMN_COMMENT"); //$NON-NLS-1$
            boolean unsigned = columnType.toLowerCase().indexOf("unsigned") >= 0; //$NON-NLS-1$

            int dataLength = (dataCharLength != null && dataCharLength.intValue() > 0)
                    ? dataCharLength.intValue()
                    : numericLength > 0 ? numericLength : 0;
            dataPrecision = Math.max(dataPrecision, 0);
            // Workaround the bloody management of MySQL default values !!
            // TODO: Check for JDBC updates of the mysql driver...
            if ("CURRENT_TIMESTAMP".equalsIgnoreCase(dataDefault)) { //$NON-NLS-1$
                dataDefault = null;
            }
            if (dataDefault != null && !"".equals(dataDefault)) { //$NON-NLS-1$
                // Adding quotes and escaping quotes in default values for
                // string datatypes
                if (datatypeProvider.listStringDatatypes().contains(datatype)) {
                    dataDefault = "'" + dataDefault.replace("'", "''") + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                }
            }

            /*
             * Since 1.0.6, for every type, we base our capture on the
             * COLUMN_TYPE information which provides much more accurate
             * information (mostly on length/precision) and is the field
             * used by the MySQL "show create table" command.
             */
            if (datatype.startsWith("ENUM") || datatype.startsWith("SET")) { //$NON-NLS-1$ //$NON-NLS-2$
                // Taking the whole column type
                dataLength = 0;
                dataPrecision = 0;
                datatype = columnType;
            } else {
                if (columnType != null) {
                    final String mysqlType = columnType.toUpperCase();
                    // Parsing the type as "datatype(length,precision)"
                    int ind = mysqlType.indexOf('(');
                    // Have we got a size ?
                    if (ind > 0) {
                        try {
                            // Data type is the text before bracket
                            datatype = mysqlType.substring(0, ind).toUpperCase();
                            int comma = mysqlType.indexOf(',', ind);
                            int rightpar = mysqlType.indexOf(')', ind);
                            // Have we got a comma ?
                            if (comma > 0) {
                                // The comma separates length and precision
                                dataLength = Integer.parseInt(mysqlType.substring(ind + 1, comma));
                                dataPrecision = Integer.parseInt(mysqlType.substring(comma + 1, rightpar));
                            } else {
                                // Otherwise we got a 0 precision
                                dataLength = Integer.parseInt(mysqlType.substring(ind + 1, rightpar));
                                dataPrecision = 0;
                            }
                        } catch (NumberFormatException nfe) {
                            // Unknown type definition, resetting everything
                            // to 0
                            LOGGER.warn("Could not parse the data type [" + columnType + "] of column ["
                                    + tableName + "." + columnName + "]: " //$NON-NLS-1$ //$NON-NLS-2$
                                    + "data type could be incorrect");
                            datatype = columnType;
                            dataLength = 0;
                            dataPrecision = 0;
                        }
                    } else {
                        // No size definition, resetting everything to 0
                        datatype = mysqlType;
                        dataLength = 0;
                        dataPrecision = 0;
                    }
                }
            }

            // Specific behavior when data type name contains the "UNSIGNED"
            // keyword
            if (datatype.indexOf("UNSIGNED") > -1) { //$NON-NLS-1$
                unsigned = true;
                datatype = datatype.replaceAll("UNSIGNED", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$
            }

            IDatatype d = new Datatype(datatype, dataLength, dataPrecision);
            IMySQLColumn c = new MySQLColumn(columnName, colComments, d, rank - 1);
            // (IBasicColumn)ControllerFactory.getController(IElementType.COLUMN).emptyInstance(t);
            c.setName(columnName);
            c.setDescription(colComments);
            d.setUnsigned(unsigned);
            c.setDatatype(d);
            c.setRank(rank - 1);
            c.setAutoIncremented(autoInc);
            c.setNotNull(!nullable);
            c.setDefaultExpr(dataDefault == null ? "" : dataDefault.trim()); //$NON-NLS-1$

            // Character set management
            final String tabCharset = table.getCharacterSet();
            final String tabCollation = table.getCollation();

            if (charset != null && !charset.equals(tabCharset)) {
                c.setCharacterSet(charset);
            }
            if (collation != null && !collation.equals(tabCollation)
                    && !collation.equals(mysqlModelService.getDefaultCollation(charset))) {
                c.setCollation(collation);
            }
            // TODO Warning: might cause save problems / column list
            // duplicates because
            // adding unsaved columns
            c.setParent(table);
            table.addColumn(c);
            // Storing columns for later use
            final String colName = CaptureHelper.getUniqueColumnName(c);
            columnsMap.put(colName, c);

        }
    } finally {
        CaptureHelper.safeClose(rset, null);
    }

    return columnsMap;
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

@Test
public void testDecimal() throws SQLException {
    trace("test DECIMAL");
    ResultSet rs;
    Object o;/*from ww  w  .j  a v  a 2  s  .c om*/

    stat = conn.createStatement();
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(21,-1,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(22,.0,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(23,1.0,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(24,12345678.89,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(25,99999998.99,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(26,-99999998.99,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(27,-99999998.99,9,'testDecimal')");
    rs = stat.executeQuery("SELECT column1,column5 FROM test where column3='testDecimal' ORDER BY column1");
    BigDecimal bd;
    rs.next();
    assertTrue(rs.getInt(1) == 21);
    assertTrue(!rs.wasNull());
    assertTrue(rs.getInt(2) == -1);
    assertTrue(!rs.wasNull());
    bd = rs.getBigDecimal(2);
    assertTrue(bd.compareTo(new BigDecimal("-1.00")) == 0);
    assertTrue(!rs.wasNull());
    o = rs.getObject(2);
    trace(o.getClass().getName());
    assertTrue(o instanceof Double);
    assertTrue(new BigDecimal((Double) o).compareTo(new BigDecimal("-1.00")) == 0);
    rs.next();
    assertTrue(rs.getInt(1) == 22);
    assertTrue(!rs.wasNull());
    assertTrue(rs.getInt(2) == 0);
    assertTrue(!rs.wasNull());
    bd = rs.getBigDecimal(2);
    assertTrue(bd.compareTo(new BigDecimal("0.00")) == 0);
    assertTrue(!rs.wasNull());
    rs.next();
    checkColumnBigDecimal(rs, 2, 1, "1.00");
    rs.next();
    checkColumnBigDecimal(rs, 2, 12345679, "12345678.89");
    rs.next();
    checkColumnBigDecimal(rs, 2, 99999999, "99999998.99");
    rs.next();
    checkColumnBigDecimal(rs, 2, -99999999, "-99999998.99");
    // assertTrue(!rs.next());
}

From source file:eionet.eunis.stripes.actions.CountryFactsheetActionBean.java

/**
 * @param con Connection/*from  www .  j a  va 2s. c  o m*/
 * @param noSitesA List of 'Total number of sites'
 * @param areaTotalA List of 'Total area(ha)'
 * @throws SQLException
 */
private void populateDesignations(Connection con, List noSitesA, List areaTotalA) throws SQLException {
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {

        String sql = "SELECT DESIG.ID_DESIGNATION as DESIG_ID, " + " DESIG.ID_GEOSCOPE as GEO, "
                + " DESIG.DESCRIPTION_EN as TITLE, " + " count(distinct SITES.ID_SITE) as SITE_COUNT, "
                + " sum(SITES.AREA) as TOT_AREA , " + " DESIG.* " + " from "
                + " chm62edt_designations as DESIG "
                + " inner join chm62edt_sites as SITES on (DESIG.ID_DESIGNATION=SITES.ID_DESIGNATION and DESIG.ID_GEOSCOPE=SITES.ID_GEOSCOPE) "
                + " inner join chm62edt_nature_object_geoscope as GEO on (SITES.ID_NATURE_OBJECT=GEO.ID_NATURE_OBJECT) "
                + " inner join chm62edt_country as CNTRY on (GEO.ID_GEOSCOPE = CNTRY.ID_GEOSCOPE) " + " where "
                + statisticsBean.prepareSQLForFindSites() + " group by "
                + "DESIG.ID_DESIGNATION, DESIG.ID_GEOSCOPE;";

        ps = con.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            noSitesA.add(rs.getLong("SITE_COUNT"));
            areaTotalA.add(rs.getLong("TOT_AREA"));
            Chm62edtDesignationsPersist persist = new Chm62edtDesignationsPersist();

            persist.setDescriptionEn(rs.getString("TITLE"));
            persist.setIdGeoscope(rs.getString("GEO"));
            persist.setDescription(rs.getString("DESCRIPTION"));
            persist.setNationalCategory(rs.getString("NATIONAL_CATEGORY"));
            persist.setIdDc(rs.getInt("ID_DC"));
            persist.setCddaSites(rs.getString("CDDA_SITES"));
            persist.setOriginalDataSource(rs.getString("ORIGINAL_DATASOURCE"));
            persist.setReferenceArea(rs.getBigDecimal("REFERENCE_AREA"));
            persist.setNationalLaw(rs.getString("NATIONAL_LAW"));
            persist.setNationalLawReference(rs.getString("NATIONAL_LAW_REFERENCE"));
            persist.setNationalLawAgency(rs.getString("NATIONAL_LAW_AGENCY"));
            persist.setDataSource(rs.getString("DATA_SOURCE"));
            persist.setReferenceNumber(rs.getBigDecimal("REFERENCE_NUMBER"));
            persist.setReferenceDate(rs.getString("REFERENCE_DATE"));
            persist.setRemark(rs.getString("REMARK"));
            persist.setRemarkSource(rs.getString("REMARK_SOURCE"));
            persist.setTotalArea(rs.getBigDecimal("TOTAL_AREA"));
            persist.setIdDesignation(rs.getString("DESIG_ID"));

            if (designations == null) {
                designations = new ArrayList();
            }
            designations.add(persist);

        }
    } finally {
        SQLUtilities.closeAll(null, ps, rs);
    }
}

From source file:com.nextep.designer.sqlgen.mssql.impl.MSSQLCapturer.java

/**
 * @param context a {@link ICaptureContext} representing the current capture context
 * @param monitor the {@link IProgressMonitor} to notify while capturing objects
 * @return a <code>Map</code> of all identity columns in the current database hashed by a
 *         <code>MultiKey</code> containing the schema and table names of the parent tables.
 *         Each identity column is represented by a <code>MultiKey</code> containing the name of
 *         the column, followed by the seed and increment attributes
 *//*from w  w w .  j a va 2 s  .c  o m*/
private Map<MultiKey, MultiKey> getIdentityColumnsAttributes(ICaptureContext context,
        IProgressMonitor monitor) {
    monitor.subTask("Retrieving identity columns attributes...");
    final Map<MultiKey, MultiKey> attributes = new HashMap<MultiKey, MultiKey>();
    final String schema = context.getSchema();

    Connection conn = (Connection) context.getConnectionObject();
    PreparedStatement prepStmt = null;
    ResultSet rset = null;
    try {
        String query = "SELECT s.name AS schema_name, t.name AS table_name, c.name AS column_name, " //$NON-NLS-1$
                + "  c.seed_value, c.increment_value, IDENT_CURRENT(s.name + '.' + t.name) AS last_value " //$NON-NLS-1$
                + "FROM sys.schemas AS s " //$NON-NLS-1$
                + "  JOIN sys.tables AS t ON t.schema_id = s.schema_id " //$NON-NLS-1$
                + "  JOIN sys.identity_columns AS c ON c.object_id = t.object_id"; //$NON-NLS-1$
        if (schema != null) {
            query += " WHERE s.name = ?"; //$NON-NLS-1$
        }

        prepStmt = conn.prepareStatement(query);
        if (schema != null) {
            prepStmt.setString(1, schema);
        }

        rset = prepStmt.executeQuery();
        while (rset.next()) {
            monitor.worked(1);
            final String schemaName = rset.getString("schema_name"); //$NON-NLS-1$
            final String tableName = rset.getString("table_name"); //$NON-NLS-1$
            final String columnName = rset.getString("column_name"); //$NON-NLS-1$
            final int seed = rset.getInt("seed_value"); //$NON-NLS-1$
            final int increment = rset.getInt("increment_value"); //$NON-NLS-1$
            final BigDecimal lastValue = rset.getBigDecimal("last_value"); //$NON-NLS-1$

            // We check that the schema name is not null, and that the table and column names
            // are not null and not empty.
            if (schemaName != null && tableName != null && !"".equals(tableName.trim()) //$NON-NLS-1$
                    && columnName != null && !"".equals(columnName.trim())) { //$NON-NLS-1$
                if (LOGGER.isDebugEnabled()) {
                    String logPrefix = "[" + schemaName + "." + tableName + "." + columnName //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                            + "] "; //$NON-NLS-1$
                    LOGGER.debug("= " + logPrefix + "Identity Property Metadata ="); //$NON-NLS-1$ //$NON-NLS-2$
                    LOGGER.debug(logPrefix + "[SEED] " + seed); //$NON-NLS-1$
                    LOGGER.debug(logPrefix + "[INCREMENT] " + increment); //$NON-NLS-1$
                    LOGGER.debug(logPrefix + "[LAST_VALUE] " + lastValue); //$NON-NLS-1$
                }

                attributes.put(new MultiKey(schemaName, tableName), new MultiKey(columnName, seed, increment));
            }
        }
    } catch (SQLException sqle) {
        LOGGER.error("Unable to fetch identity columns attributes from SQL Server server: " + sqle.getMessage(),
                sqle);
    } finally {
        CaptureHelper.safeClose(rset, prepStmt);
    }

    return attributes;
}

From source file:com.nec.harvest.service.impl.PurchaseServiceImlp.java

/** {@inheritDoc} */
@Override// www .  ja va  2 s  .co  m
public List<PurchaseBean> findByOrgCodeAndMonthAndSQL(String strCode, String getSudo, String sql)
        throws ServiceException {
    if (StringUtils.isEmpty(strCode)) {
        throw new IllegalArgumentException("Orginazation code must not be null or empty");
    }
    if (StringUtils.isEmpty(getSudo)) {
        throw new IllegalArgumentException("Month must not be null or empty");
    }
    if (StringUtils.isEmpty(sql)) {
        throw new IllegalArgumentException("Sql must not be null or empty");
    }

    Connection connection = null;
    PreparedStatement preSmt = null;
    ResultSet rs = null;

    // Kind of SQL
    boolean isFindByOrgCodeAndMonthSQL = sql
            .equals(SqlConstants.SQL_FIND_PURCHASE_DATA_HEADER_BY_ORGCODE_AND_MONTH);

    List<PurchaseBean> purchases = new ArrayList<PurchaseBean>();

    try {
        connection = HibernateSessionManager.getConnection();
        preSmt = connection.prepareStatement(sql);
        preSmt.setString(1, getSudo);
        preSmt.setString(2, strCode);

        rs = preSmt.executeQuery();
        while (rs.next()) {
            PurchaseBean purchase;

            String srsCode = rs.getString("srsCode");
            String ctgCode = rs.getString("ctgCode");
            String wakuNum = rs.getString("wakuNum");

            String srsName = null;
            String srsNameR = null;
            String ctgName = null;
            String ctgNameR = null;

            int updNo = 0;
            int kingaku = 0;

            Date srDate = null;
            String gnrKbn1 = null;

            if (isFindByOrgCodeAndMonthSQL) {
                srsName = rs.getString("srsName");
                srsNameR = rs.getString("srsNameR");
                ctgName = rs.getString("ctgName");
                ctgNameR = rs.getString("ctgNameR");

                // New an instance
                purchase = new PurchaseBean(srsCode, srsName, srsNameR, ctgCode, ctgName, ctgNameR, wakuNum,
                        updNo, srDate, kingaku, gnrKbn1);
            } else {
                updNo = rs.getInt("updNo");
                srDate = rs.getDate("srDate");
                kingaku = rs.getBigDecimal("kingaku").intValue();
                gnrKbn1 = rs.getString("gnrKbn1");

                // New an instance
                purchase = new PurchaseBean(srsCode, srsName, srsNameR, ctgCode, ctgName, ctgNameR, wakuNum,
                        updNo, srDate, kingaku, gnrKbn1);
            }
            purchases.add(purchase);
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }

            if (preSmt != null) {
                preSmt.close();
            }

            if (connection != null) {
                connection.close();
            }
        } catch (SQLException ex) {
            logger.error(ex.getMessage(), ex);
        }
    }

    if (purchases.size() <= 0) {
        throw new ObjectNotFoundException(
                "Could not find any purchase in the database for the organization's code " + strCode
                        + " in month " + getSudo);
    }

    return purchases;
}

From source file:com.sangupta.fileanalysis.db.DBResultViewer.java

/**
 * View resutls of a {@link ResultSet}.//  w w w  .  j av  a2  s .  com
 * 
 * @param resultSet
 * @throws SQLException 
 */
public void viewResult(ResultSet resultSet) throws SQLException {
    if (resultSet == null) {
        // nothing to do
        return;
    }

    // collect the meta
    ResultSetMetaData meta = resultSet.getMetaData();

    final int numColumns = meta.getColumnCount();
    final int[] displaySizes = new int[numColumns + 1];
    final int[] colType = new int[numColumns + 1];

    for (int index = 1; index <= numColumns; index++) {
        colType[index] = meta.getColumnType(index);
        displaySizes[index] = getColumnSize(meta.getTableName(index), meta.getColumnName(index),
                colType[index]);
    }

    // display the header row
    for (int index = 1; index <= numColumns; index++) {
        center(meta.getColumnLabel(index), displaySizes[index]);
    }
    System.out.println("|");
    for (int index = 1; index <= numColumns; index++) {
        System.out.print("+" + StringUtils.repeat('-', displaySizes[index] + 2));
    }
    System.out.println("+");

    // start iterating over the result set
    int rowsDisplayed = 0;
    int numRecords = 0;
    while (resultSet.next()) {
        // read and display the value
        rowsDisplayed++;
        numRecords++;

        for (int index = 1; index <= numColumns; index++) {
            switch (colType[index]) {
            case Types.DECIMAL:
            case Types.DOUBLE:
            case Types.REAL:
                format(resultSet.getDouble(index), displaySizes[index]);
                continue;

            case Types.INTEGER:
            case Types.SMALLINT:
                format(resultSet.getInt(index), displaySizes[index]);
                continue;

            case Types.VARCHAR:
                format(resultSet.getString(index), displaySizes[index], false);
                continue;

            case Types.TIMESTAMP:
                format(resultSet.getTimestamp(index), displaySizes[index]);
                continue;

            case Types.BIGINT:
                format(resultSet.getBigDecimal(index), displaySizes[index]);
                continue;
            }
        }

        // terminator for row and new line
        System.out.println("|");

        // check for rows displayed
        if (rowsDisplayed == 20) {
            // ask the user if more data needs to be displayed
            String cont = ConsoleUtils.readLine("Type \"it\" for more: ", true);
            if (!"it".equalsIgnoreCase(cont)) {
                break;
            }

            // continue;
            rowsDisplayed = 0;
            continue;
        }
    }

    System.out.println("\nTotal number of records found: " + numRecords);
}

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

public void testDataTypes() throws Exception {
    Statement stmt = con.createStatement();

    ResultSet res = stmt.executeQuery("select * from " + dataTypeTableName + " order by c1");
    ResultSetMetaData meta = res.getMetaData();

    // row 1// w w w. j av  a 2  s  .  c  o  m
    assertTrue(res.next());
    // skip the last (partitioning) column since it is always non-null
    for (int i = 1; i < meta.getColumnCount(); i++) {
        assertNull(res.getObject(i));
    }

    // row 2
    assertTrue(res.next());
    assertEquals(-1, res.getInt(1));
    assertEquals(false, res.getBoolean(2));
    assertEquals(-1.1d, res.getDouble(3));
    assertEquals("", res.getString(4));
    assertEquals("[]", res.getString(5));
    assertEquals("{}", res.getString(6));
    assertEquals("{}", res.getString(7));
    assertEquals("[null, null, null]", res.getString(8));
    assertEquals(-1, res.getByte(9));
    assertEquals(-1, res.getShort(10));
    assertEquals(-1.0f, res.getFloat(11));
    assertEquals(-1, res.getLong(12));
    assertEquals("[]", res.getString(13));
    assertEquals("{}", res.getString(14));
    assertEquals("[null, null]", res.getString(15));
    assertEquals("[]", res.getString(16));
    assertEquals(null, res.getString(17));
    assertEquals(null, res.getTimestamp(17));
    assertEquals(null, res.getBigDecimal(18));
    assertEquals(null, res.getString(20));
    assertEquals(null, res.getDate(20));

    // row 3
    assertTrue(res.next());
    assertEquals(1, res.getInt(1));
    assertEquals(true, res.getBoolean(2));
    assertEquals(1.1d, res.getDouble(3));
    assertEquals("1", res.getString(4));
    assertEquals("[1, 2]", res.getString(5));
    assertEquals("{1=x, 2=y}", res.getString(6));
    assertEquals("{k=v}", res.getString(7));
    assertEquals("[a, 9, 2.2]", res.getString(8));
    assertEquals(1, res.getByte(9));
    assertEquals(1, res.getShort(10));
    assertEquals(1.0f, res.getFloat(11));
    assertEquals(1, res.getLong(12));
    assertEquals("[[a, b], [c, d]]", res.getString(13));
    assertEquals("{1={11=12, 13=14}, 2={21=22}}", res.getString(14));
    assertEquals("[1, [2, x]]", res.getString(15));
    assertEquals("[[{}, 1], [{c=d, a=b}, 2]]", res.getString(16));
    assertEquals("2012-04-22 09:00:00.123456789", res.getString(17));
    assertEquals("2012-04-22 09:00:00.123456789", res.getTimestamp(17).toString());
    assertEquals("123456789.0123456", res.getBigDecimal(18).toString());
    assertEquals("2013-01-01", res.getString(20));
    assertEquals("2013-01-01", res.getDate(20).toString());

    // test getBoolean rules on non-boolean columns
    assertEquals(true, res.getBoolean(1));
    assertEquals(true, res.getBoolean(4));

    // no more rows
    assertFalse(res.next());
}

From source file:com.runwaysdk.dataaccess.database.general.Oracle.java

/**
 * @see com.runwaysdk.dataaccess.database.relationship.AbstractDatabase#getChildCountForParent(java.lang.String, java.lang.String)
 *//* w w  w .java 2 s . c  o  m*/
public long getChildCountForParent(String parent_id, String relationshipTableName) {
    String query = " SELECT COUNT(*) AS CT \n" + " FROM " + relationshipTableName + " \n" + " WHERE "
            + RelationshipDAOIF.PARENT_ID_COLUMN + " = '" + parent_id + "' \n" + " AND "
            + RelationshipDAOIF.CHILD_ID_COLUMN + " IN " + "   (SELECT DISTINCT "
            + RelationshipDAOIF.CHILD_ID_COLUMN + " \n" + "    FROM " + relationshipTableName + " \n"
            + "    WHERE " + RelationshipDAOIF.PARENT_ID_COLUMN + " = '" + parent_id + "')";

    ResultSet resultSet = this.query(query);

    long returnValue = 0;

    try {
        if (resultSet.next()) {
            BigDecimal number = (BigDecimal) resultSet.getBigDecimal("ct");
            returnValue = number.longValue();
        }
    } catch (SQLException sqlEx1) {
        Database.throwDatabaseException(sqlEx1);
    } finally {
        try {
            java.sql.Statement statement = resultSet.getStatement();
            resultSet.close();
            statement.close();
        } catch (SQLException sqlEx2) {
            Database.throwDatabaseException(sqlEx2);
        }
    }

    return returnValue;

    // Heads up:
    //    List<DynaBean> dynaBeanList = this.select(query);
    //
    //    if (dynaBeanList.size() == 0)
    //    {
    //      return 0;
    //    }
    //    else
    //    {
    //      DynaBean dynaBean = dynaBeanList.get(0);
    //      BigDecimal number = (BigDecimal)dynaBean.get("ct");
    //      return number.longValue();
    //    }
}

From source file:com.runwaysdk.dataaccess.database.general.Oracle.java

/**
 * @see com.runwaysdk.dataaccess.database.relationship.AbstractDatabase#getParentCountForChild(java.lang.String, java.lang.String)
 */// w  w  w.  j a v  a  2 s.c  o  m
public long getParentCountForChild(String child_id, String relationshipTableName) {
    String query = " SELECT COUNT(*) AS CT \n" + " FROM " + relationshipTableName + " \n" + " WHERE "
            + RelationshipDAOIF.CHILD_ID_COLUMN + " = '" + child_id + "' \n" + " AND "
            + RelationshipDAOIF.PARENT_ID_COLUMN + " IN " + "   (SELECT DISTINCT "
            + RelationshipDAOIF.PARENT_ID_COLUMN + " \n" + "    FROM " + relationshipTableName + " \n"
            + "    WHERE " + RelationshipDAOIF.CHILD_ID_COLUMN + " = '" + child_id + "')";

    ResultSet resultSet = this.query(query);

    long returnValue = 0;

    try {
        if (resultSet.next()) {
            BigDecimal number = (BigDecimal) resultSet.getBigDecimal("ct");
            returnValue = number.longValue();
        }
    } catch (SQLException sqlEx1) {
        Database.throwDatabaseException(sqlEx1);
    } finally {
        try {
            java.sql.Statement statement = resultSet.getStatement();
            resultSet.close();
            statement.close();
        } catch (SQLException sqlEx2) {
            Database.throwDatabaseException(sqlEx2);
        }
    }

    return returnValue;

    // Heads up:
    //    List<DynaBean> dynaBeanList = this.select(query);
    //
    //    if (dynaBeanList.size() == 0)
    //    {
    //      return 0;
    //    }
    //    else
    //    {
    //      DynaBean dynaBean = dynaBeanList.get(0);
    //      BigDecimal number = (BigDecimal)dynaBean.get("ct");
    //      return number.longValue();
    //    }
}