Example usage for java.sql ResultSetMetaData getColumnName

List of usage examples for java.sql ResultSetMetaData getColumnName

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnName.

Prototype

String getColumnName(int column) throws SQLException;

Source Link

Document

Get the designated column's name.

Usage

From source file:ResultsDecoratorText.java

public void write(ResultSet rs) throws IOException, SQLException {
    ResultSetMetaData md = rs.getMetaData();
    int cols = md.getColumnCount();
    for (int i = 1; i <= cols; i++) {
        print(md.getColumnName(i) + "\t");
    }//from  www .  j a va2 s  . co m
    println();
    while (rs.next()) {
        for (int i = 1; i <= cols; i++) {
            print(rs.getString(i) + "\t");
        }
        println();
    }
}

From source file:net.orpiske.ssps.common.db.MultiRsHandler.java

@Override
protected T handleRow(ResultSet rs) throws SQLException {
    T dto;/* w w  w  .j  a  v a2s  . co m*/

    try {
        dto = clazz.newInstance();
    } catch (InstantiationException e1) {
        throw new SQLException("Unable to instantiate DTO class: " + e1.getMessage(), e1);
    } catch (IllegalAccessException e1) {
        throw new SQLException("Illegal to instantiate DTO class: " + e1.getMessage(), e1);
    }

    ResultSetMetaData meta = rs.getMetaData();

    for (int i = 1; i <= meta.getColumnCount(); i++) {
        Object value = rs.getObject(i);
        String name = meta.getColumnName(i);

        try {
            /*
             * We convert the column name to a more appropriate and java like name 
             * because some columns are usually named as some_thing whereas Java 
             * properties are named someThing. This call does this conversion.
             */
            String javaProperty = NameConverter.sqlToProperty(name);

            PropertyUtils.setSimpleProperty(dto, javaProperty, value);
        } catch (Exception e) {
            throw new SQLException("Unable to set property " + name + " for bean" + dto.getClass(), e);
        }
    }

    return dto;
}

From source file:net.orpiske.ssps.common.registry.SoftwareInventoryRsHandler.java

@Override
public SoftwareInventoryDto handle(ResultSet rs) throws SQLException {

    // No records to handle :O
    if (!rs.next()) {
        return null;
    }// w w w .j  ava2 s  .  c  o  m

    ResultSetMetaData meta = rs.getMetaData();

    for (int i = 1; i <= meta.getColumnCount(); i++) {
        Object value = rs.getObject(i);
        String name = meta.getColumnName(i);

        try {
            /*
             * We convert the column name to a more appropriate and java like name 
             * because some columns are usually named as some_thing whereas Java 
             * properties are named someThing. This call does this conversion.
             */
            String javaProperty = NameConverter.sqlToProperty(name);

            if (javaProperty.equals("version")) {
                Version version = Version.toVersion((String) value);

                PropertyUtils.setSimpleProperty(dto, javaProperty, version);
            } else {
                PropertyUtils.setSimpleProperty(dto, javaProperty, value);
            }

        } catch (Exception e) {
            throw new SQLException("Unable to set property " + name + " for bean" + dto.getClass(), e);
        }
    }

    return dto;
}

From source file:net.orpiske.ssps.common.repository.search.cache.PackageCacheRsHandler.java

@Override
public PackageInfo handle(ResultSet rs) throws SQLException {

    // No records to handle :O
    if (!rs.next()) {
        return null;
    }//from  w  w w  .ja v a2 s  . co  m

    ResultSetMetaData meta = rs.getMetaData();

    for (int i = 1; i <= meta.getColumnCount(); i++) {
        Object value = rs.getObject(i);
        String name = meta.getColumnName(i);

        try {
            /*
             * We convert the column name to a more appropriate and java like name 
             * because some columns are usually named as some_thing whereas Java 
             * properties are named someThing. This call does this conversion.
             */
            String javaProperty = NameConverter.sqlToProperty(name);

            if (javaProperty.equals("version")) {
                Version version = Version.toVersion((String) value);

                PropertyUtils.setSimpleProperty(dto, javaProperty, version);
            } else {
                PropertyUtils.setSimpleProperty(dto, javaProperty, value);
            }

        } catch (Exception e) {
            throw new SQLException("Unable to set property " + name + " for bean" + dto.getClass(), e);
        }
    }

    return dto;
}

From source file:org.apache.fineract.infrastructure.dataexport.helper.DataExportUtils.java

/**
 * Gets the meta data of the columns of the specified table
 * //from  w w  w  . j av a2 s  . c  om
 * @param tableName
 * @param jdbcTemplate
 * @return List of {@link EntityColumnMetaData} objects
 */
public static List<EntityColumnMetaData> getTableColumnsMetaData(final String tableName,
        final JdbcTemplate jdbcTemplate) {
    final List<EntityColumnMetaData> entityColumnsMetaData = new ArrayList<>();
    final List<String> columnNames = new ArrayList<>();
    final DataExportCoreTable coreTable = DataExportCoreTable.newInstance(tableName);
    Set<String> columnsToBeRemovedFromListsOfEntityColumns = new HashSet<>(
            Arrays.asList(DataExportEntityColumnName.TRANSFER_TO_OFFICE_ID, DataExportEntityColumnName.VERSION,
                    DataExportEntityColumnName.IMAGE_ID, DataExportEntityColumnName.ACCOUNT_TYPE_ENUM,
                    DataExportEntityColumnName.DEPOSIT_TYPE_ENUM, DataExportEntityColumnName.SUB_STATUS,
                    DataExportEntityColumnName.FULL_NAME));

    try {
        // see - http://dev.mysql.com/doc/refman/5.7/en/limit-optimization.html
        // LIMIT 0 quickly returns an empty set. This can be useful for checking the validity of a query. 
        // It can also be employed to obtain the types of the result columns if you are using a MySQL API 
        // that makes result set metadata available.
        final ResultSetMetaData resultSetMetaData = jdbcTemplate
                .query("select * from " + tableName + " limit 0", new ResultSetExtractor<ResultSetMetaData>() {

                    @Override
                    public ResultSetMetaData extractData(ResultSet rs)
                            throws SQLException, DataAccessException {
                        return rs.getMetaData();
                    }
                });

        if (resultSetMetaData != null) {
            final int numberOfColumns = resultSetMetaData.getColumnCount();

            for (int i = 1; i <= numberOfColumns; i++) {
                String columnName = resultSetMetaData.getColumnName(i);
                String columnLabel = resultSetMetaData.getColumnName(i);
                String columnType = resultSetMetaData.getColumnTypeName(i);
                Integer columnIsNullable = resultSetMetaData.isNullable(i);
                boolean isNullable = (columnIsNullable != 0);

                if (coreTable != null) {
                    switch (coreTable) {
                    case M_LOAN_TRANSACTION:
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.UNRECOGNIZED_INCOME_PORTION);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.SUSPENDED_INTEREST_PORTION_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.SUSPENDED_FEE_CHARGES_PORTION_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.SUSPENDED_PENALTY_CHARGES_PORTION_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.OUTSTANDING_LOAN_BALANCE_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.RECOVERED_PORTION_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.PAYMENT_DETAIL_ID);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.OFFICE_ID);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.IS_ACCCOUNT_TRANSFER);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.APPUSER_ID);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.EXTERNAL_ID);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.CREATED_DATE);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.TRANSACTION_TYPE_ENUM);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.LOAN_ID);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.AMOUNT);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.PRINCIPAL_PORTION_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.INTEREST_PORTION_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.FEE_CHARGES_PORTION_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.PENALTY_CHARGES_PORTION_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.OVERPAYMENT_PORTION_DERIVED);
                        break;

                    case M_SAVINGS_ACCOUNT_TRANSACTION:
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.OVERDRAFT_AMOUNT_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.RUNNING_BALANCE_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.CUMULATIVE_BALANCE_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.BALANCE_NUMBER_OF_DAYS_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.BALANCE_END_DATE_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.CREATED_DATE);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.TRANSACTION_TYPE_ENUM);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.APPUSER_ID);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.SAVINGS_ACCOUNT_ID);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.AMOUNT);
                        break;

                    case M_LOAN_REPAYMENT_SCHEDULE:
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.ID);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.LOAN_ID);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.FROMDATE);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.INSTALLMENT);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.PRINCIPAL_COMPLETED_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.PRINCIPAL_WRITTENOFF_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.INTEREST_COMPLETED_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.INTEREST_WAIVED_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.INTEREST_WRITTENOFF_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.ACCRUAL_INTEREST_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.SUSPENDED_INTEREST_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.FEE_CHARGES_WRITTENOFF_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.FEE_CHARGES_COMPLETED_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.FEE_CHARGES_WAIVED_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.ACCRUAL_FEE_CHARGES_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.SUSPENDED_FEE_CHARGES_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.PENALTY_CHARGES_COMPLETED_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.PENALTY_CHARGES_WAIVED_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.PENALTY_CHARGES_WRITTEN_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.ACCRUAL_PENALTY_CHARGES_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.SUSPENDED_PENALTY_CHARGES_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.TOTAL_PAID_IN_ADVANCE_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.TOTAL_PAID_LATE_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.COMPLETED_DERIVED);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.CREATED_BY_ID);
                        columnsToBeRemovedFromListsOfEntityColumns.add(DataExportEntityColumnName.CREATED_DATE);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.LAST_MODIFIED_BY_ID);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.LAST_MODIFIED_DATE);
                        columnsToBeRemovedFromListsOfEntityColumns
                                .add(DataExportEntityColumnName.RECALCULATED_INTEREST_COMPONENT);
                        break;

                    default:
                        break;
                    }
                }

                if (!columnsToBeRemovedFromListsOfEntityColumns.contains(columnName)) {
                    if (columnName.equals(DataExportEntityColumnName.ID)) {
                        columnLabel = DataExportEntityColumnName.TRANSACTION_ID;
                    }
                    EntityColumnMetaData entityColumnMetaData = EntityColumnMetaData.newInstance(columnName,
                            columnLabel, columnType, isNullable);

                    entityColumnsMetaData.add(entityColumnMetaData);
                    columnNames.add(columnName);
                }
            }
        }
    }

    catch (Exception exception) {
        exception.printStackTrace();
    }

    return entityColumnsMetaData;
}

From source file:org.apache.kylin.jdbc.KylinConnectionTest.java

@Test
public void testPrepareStatementWithMockHttp() throws IOException, SQLException {
    String sql = "select 1 as val";
    try (KylinConnection connection = getConnectionWithMockHttp()) {

        // mock http
        HttpResponse response = TestUtil.mockHttpResponseWithFile(200, "OK", "query.json");
        when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(response);

        try (ResultSet resultSet = connection.prepareStatement(sql).executeQuery()) {
            assertTrue(resultSet.next());
            ResultSetMetaData metaData = resultSet.getMetaData();
            assertEquals("VAL", metaData.getColumnName(1));
            assertEquals(1, resultSet.getInt("VAL"));
        }//from w  w w  .  java2  s .c  o m
    }
}

From source file:org.apache.kylin.jdbc.KylinConnectionTest.java

@Test
public void testPrepareStatementWithMockKylinClient() throws SQLException, IOException {
    String sql = "select 1 as val";
    // mock client
    when(client.executeQuery(anyString(), Mockito.<List<Object>>any(), Mockito.<Map<String, String>>any()))
            .thenReturn(getMockResult());

    try (KylinConnection conn = getConnectionWithMockClient()) {
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        try (ResultSet resultSet = preparedStatement.executeQuery()) {
            verify(client).executeQuery(eq(sql), Mockito.<List<Object>>any(),
                    Mockito.<Map<String, String>>any());

            assertTrue(resultSet.next());
            ResultSetMetaData metaData = resultSet.getMetaData();
            assertEquals("VAL", metaData.getColumnName(1));
            assertEquals(1, resultSet.getInt("VAL"));
        }/*  w  w w. j a  v a  2  s . c om*/
    }
}

From source file:annis.sqlgen.AnnotatedSpanExtractor.java

@Override
public AnnotatedSpan mapRow(ResultSet resultSet, int rowNum) throws SQLException {
    long id = resultSet.getLong("id");
    String coveredText = resultSet.getString("span");

    Array arrayAnnotation = resultSet.getArray("annotations");
    ResultSetMetaData rsMeta = resultSet.getMetaData();
    Array arrayMeta = null;/*w ww .j  av a  2 s .  c o m*/
    for (int i = 1; i <= rsMeta.getColumnCount(); i++) {
        if ("metadata".equals(rsMeta.getColumnName(i))) {
            arrayMeta = resultSet.getArray(i);
            break;
        }
    }

    List<Annotation> annotations = extractAnnotations(arrayAnnotation);
    List<Annotation> metaData = arrayMeta == null ? new LinkedList<Annotation>()
            : extractAnnotations(arrayMeta);

    // create key
    Array sqlKey = resultSet.getArray("key");
    Validate.isTrue(!resultSet.wasNull(), "Match group identifier must not be null");
    Validate.isTrue(sqlKey.getBaseType() == Types.BIGINT,
            "Key in database must be from the type \"bigint\" but was \"" + sqlKey.getBaseTypeName() + "\"");

    List<Long> key = Arrays.asList((Long[]) sqlKey.getArray());

    return new AnnotatedSpan(id, coveredText, annotations, metaData, key);
}

From source file:net.sourceforge.seqware.webservice.resources.queries.GenericDBResource.java

private String printResultSet(ResultSet rs) throws SQLException {
    StringBuilder s = new StringBuilder();
    ResultSetMetaData rsmd = rs.getMetaData();
    int numColumns = rsmd.getColumnCount();
    //header/*from  w  ww  .  j a  va2s. c om*/
    for (int i = 1; i <= numColumns; i++) {
        s.append(rsmd.getColumnName(i));
        s.append("\t");
    }
    //values
    while (rs.next()) {
        for (int i = 1; i <= numColumns; i++) {
            s.append(rs.getString(i));
            s.append("\t");
        }
        s.append("\n");
    }

    return s.toString();
}

From source file:org.apache.drill.jdbc.test.JdbcTestQueryBase.java

protected void testQuery(String sql) throws Exception {
    boolean success = false;
    try (Connection c = DriverManager.getConnection("jdbc:drill:zk=local", null);) {
        for (int x = 0; x < 1; x++) {
            Stopwatch watch = new Stopwatch().start();
            Statement s = c.createStatement();
            ResultSet r = s.executeQuery(sql);
            boolean first = true;
            while (r.next()) {
                ResultSetMetaData md = r.getMetaData();
                if (first == true) {
                    for (int i = 1; i <= md.getColumnCount(); i++) {
                        System.out.print(md.getColumnName(i));
                        System.out.print('\t');
                    }//w ww.j a  v  a2  s  .c om
                    System.out.println();
                    first = false;
                }

                for (int i = 1; i <= md.getColumnCount(); i++) {
                    System.out.print(r.getObject(i));
                    System.out.print('\t');
                }
                System.out.println();
            }

            System.out.println(
                    String.format("Query completed in %d millis.", watch.elapsed(TimeUnit.MILLISECONDS)));
        }

        System.out.println("\n\n\n");
        success = true;
    } finally {
        if (!success)
            Thread.sleep(2000);
    }
}