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:jp.mathes.databaseWiki.db.postgres.PostgresBackend.java

@Override
public List<Row> executeQuery(final String user, final String password, final String db, final String query)
        throws BackendException {
    Statement st = null;/*from www.j a va2s .  co m*/
    Connection conn = null;
    ResultSet rs = null;
    List<Row> result = new LinkedList<Row>();
    try {
        conn = this.connectToDB(user, password, db);
        st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.logString(query.trim(), user);
        rs = st.executeQuery(query.trim());
        while (rs.next()) {
            Row row = new PostgresRow();
            ResultSetMetaData metaData = rs.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                row.getFields().add(rs.getObject(i));
                row.getFieldsByName().put(metaData.getColumnName(i), rs.getObject(i));
            }
            result.add(row);
        }
    } catch (SQLException e) {
        throw new BackendException(e);
    } catch (ClassNotFoundException e) {
        throw new BackendException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(st);
        DbUtils.closeQuietly(conn);
    }
    return result;
}

From source file:com.abixen.platform.service.businessintelligence.multivisualization.service.impl.JsonFilterServiceImpl.java

private Map<String, String> getColumnTypeMapping(ResultSetMetaData rsmd) throws SQLException {
    int columnCount = rsmd.getColumnCount();
    Map<String, String> columnTypeMapping = new HashMap<>();

    IntStream.range(1, columnCount + 1).forEach(i -> {
        try {/*w  w  w .j  a  va  2  s  .com*/
            String columnTypeName = rsmd.getColumnTypeName(i);
            if ("BIGINT".equals(columnTypeName)) {
                columnTypeName = "INTEGER";
            }
            if ("VARCHAR".equals(columnTypeName)) {
                columnTypeName = "STRING";
            }
            if ("FLOAT8".equals(columnTypeName)) {
                columnTypeName = "DOUBLE";
            }
            columnTypeMapping.put(rsmd.getColumnName(i).toUpperCase(), columnTypeName.toUpperCase());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
    return columnTypeMapping;
}

From source file:org.apache.kylin.query.adhoc.PushDownRunnerJdbcImpl.java

@Override
public void executeQuery(String query, List<List<String>> results, List<SelectedColumnMeta> columnMetas)
        throws Exception {
    Statement statement = null;/*  ww w. j a  va2  s. c o  m*/
    Connection connection = this.getConnection();
    ResultSet resultSet = null;

    //extract column metadata
    ResultSetMetaData metaData = null;
    int columnCount = 0;
    try {
        statement = connection.createStatement();
        resultSet = statement.executeQuery(query);
        extractResults(resultSet, results);
        metaData = resultSet.getMetaData();
        columnCount = metaData.getColumnCount();

        // fill in selected column meta
        for (int i = 1; i <= columnCount; ++i) {
            columnMetas.add(new SelectedColumnMeta(metaData.isAutoIncrement(i), metaData.isCaseSensitive(i),
                    false, metaData.isCurrency(i), metaData.isNullable(i), false,
                    metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i),
                    null, null, null, metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i),
                    metaData.getColumnTypeName(i), metaData.isReadOnly(i), false, false));
        }

    } catch (SQLException sqlException) {
        throw sqlException;
    } finally {
        DBUtils.closeQuietly(resultSet);
        DBUtils.closeQuietly(statement);
        closeConnection(connection);
    }

}

From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java

@Test
public void testMediumUnsignedIntShouldBeInt()
        throws SQLException, IllegalArgumentException, IllegalAccessException {
    final ResultSetMetaData metadata = mock(ResultSetMetaData.class);
    when(metadata.getColumnCount()).thenReturn(1);
    when(metadata.getColumnType(1)).thenReturn(Types.INTEGER);
    when(metadata.getPrecision(1)).thenReturn(8);
    when(metadata.isSigned(1)).thenReturn(false);
    when(metadata.getColumnName(1)).thenReturn("Col1");
    when(metadata.getTableName(1)).thenReturn("Table1");

    final ResultSet rs = mock(ResultSet.class);
    when(rs.getMetaData()).thenReturn(metadata);

    Schema schema = JdbcCommon.createSchema(rs);
    Assert.assertNotNull(schema);// w  w w  .  j av  a2  s . c o m

    Schema.Field field = schema.getField("Col1");
    Schema fieldSchema = field.schema();
    Assert.assertEquals(2, fieldSchema.getTypes().size());

    boolean foundIntSchema = false;
    boolean foundNullSchema = false;

    for (Schema type : fieldSchema.getTypes()) {
        if (type.getType().equals(Schema.Type.INT)) {
            foundIntSchema = true;
        } else if (type.getType().equals(Schema.Type.NULL)) {
            foundNullSchema = true;
        }
    }

    assertTrue(foundIntSchema);
    assertTrue(foundNullSchema);
}

From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java

@Test
public void testUnsignedIntShouldBeLong()
        throws SQLException, IllegalArgumentException, IllegalAccessException {
    final ResultSetMetaData metadata = mock(ResultSetMetaData.class);
    when(metadata.getColumnCount()).thenReturn(1);
    when(metadata.getColumnType(1)).thenReturn(Types.INTEGER);
    when(metadata.getPrecision(1)).thenReturn(10);
    when(metadata.isSigned(1)).thenReturn(false);
    when(metadata.getColumnName(1)).thenReturn("Col1");
    when(metadata.getTableName(1)).thenReturn("Table1");

    final ResultSet rs = mock(ResultSet.class);
    when(rs.getMetaData()).thenReturn(metadata);

    Schema schema = JdbcCommon.createSchema(rs);
    Assert.assertNotNull(schema);//from   ww w .  j  a v  a  2s  . c om

    Schema.Field field = schema.getField("Col1");
    Schema fieldSchema = field.schema();
    Assert.assertEquals(2, fieldSchema.getTypes().size());

    boolean foundLongSchema = false;
    boolean foundNullSchema = false;

    for (Schema type : fieldSchema.getTypes()) {
        if (type.getType().equals(Schema.Type.LONG)) {
            foundLongSchema = true;
        } else if (type.getType().equals(Schema.Type.NULL)) {
            foundNullSchema = true;
        }
    }

    assertTrue(foundLongSchema);
    assertTrue(foundNullSchema);
}

From source file:cosmos.sql.TestSql.java

public void testDistinct() throws SQLException {
    loadDriverClass();/*from   w  ww  . j  av a2s. c  o m*/
    Connection connection = null;
    Statement statement = null;
    try {
        Properties info = new Properties();
        info.put("url", JDBC_URL);
        info.put("user", USER);
        info.put("password", PASSWORD);
        connection = DriverManager.getConnection("jdbc:accumulo:cosmos//localhost", info);
        statement = connection.createStatement();
        final ResultSet resultSet = statement.executeQuery("select DISTINCT \"PAGE_ID\" from \""
                + CosmosDriver.COSMOS + "\".\"" + meataData.uuid() + "\"");
        final ResultSetMetaData metaData = resultSet.getMetaData();
        final int columnCount = metaData.getColumnCount();

        assertEquals(columnCount, 1);

        int resultsFound = 0;
        while (resultSet.next()) {
            assertEquals(metaData.getColumnName(1), "PAGE_ID");
            Object value = resultSet.getObject("PAGE_ID");

        }

        assertEquals(resultsFound, 2);
    } finally {
        close(connection, statement);
    }
}

From source file:flex.messaging.io.ASRecordSet.java

public void populate(ResultSet rs) throws IOException {

    try {// w w  w  .  ja  v  a  2 s .  c  o  m
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        String[] columnNames = new String[columnCount];

        int rowIndex = 0;
        List<List<Object>> initialData = new ArrayList<List<Object>>();
        while (rs.next()) {
            rowIndex++;
            List<Object> row = new ArrayList<Object>();
            for (int column = 0; column < columnCount; column++) {
                if (rowIndex == 1) {
                    columnNames[column] = rsmd.getColumnName(column + 1);
                }
                row.add(rs.getObject(column + 1));
            }
            if (rowIndex == 1) {
                setColumnNames(columnNames);
            }
            rows.add(row);
            if (rowIndex <= initialRowCount) {
                initialData.add(row);
            }
        }
        setTotalCount(rowIndex);
        setInitialData(initialData);
        setColumnNames(columnNames);
    } catch (SQLException e) {
        throw new IOException(e.getMessage());
    }

}

From source file:org.apache.sqoop.connector.hbase.HbaseFromInitializer.java

@Override
public Schema getSchema(InitializerContext context, LinkConfiguration linkConfig,
        FromJobConfiguration fromJobConfig) {
    executor = new HbaseExecutor(linkConfig.linkConfig);

    String schemaName = fromJobConfig.fromJobConfig.tableName;
    if (schemaName == null) {
        schemaName = "Query";
    } else if (fromJobConfig.fromJobConfig.schemaName != null) {
        schemaName = fromJobConfig.fromJobConfig.schemaName + "." + schemaName;
    }//from  w w  w. j  ava  2  s.  co m

    Schema schema = new Schema(schemaName);
    ResultSet rs = null;
    ResultSetMetaData rsmt = null;
    try {
        rs = executor.executeQuery(context.getString(HbaseConnectorConstants.CONNECTOR_JDBC_FROM_DATA_SQL)
                .replace(HbaseConnectorConstants.SQL_CONDITIONS_TOKEN, "1 = 0"));

        rsmt = rs.getMetaData();
        for (int i = 1; i <= rsmt.getColumnCount(); i++) {
            String columnName = rsmt.getColumnLabel(i);
            if (StringUtils.isEmpty(columnName)) {
                columnName = rsmt.getColumnName(i);
                if (StringUtils.isEmpty(columnName)) {
                    columnName = "Column " + i;
                }
            }
            Column column = SqlTypesUtils.sqlTypeToSchemaType(rsmt.getColumnType(i), columnName,
                    rsmt.getPrecision(i), rsmt.getScale(i));
            schema.addColumn(column);
        }

        return schema;
    } catch (SQLException e) {
        throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0016, e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.info("Ignoring exception while closing ResultSet", e);
            }
        }
        if (executor != null) {
            executor.close();
        }
    }
}

From source file:cosmos.sql.TestSql.java

@Test
public void testLimit() throws SQLException {
    loadDriverClass();/*w  w w  .ja  va 2s.  c o  m*/
    Connection connection = null;
    Statement statement = null;
    try {
        Properties info = new Properties();
        info.put("url", JDBC_URL);
        info.put("user", USER);
        info.put("password", PASSWORD);
        connection = DriverManager.getConnection("jdbc:accumulo:cosmos//localhost", info);
        statement = connection.createStatement();
        final ResultSet resultSet = statement.executeQuery("select \"PAGE_ID\" from \"" + CosmosDriver.COSMOS
                + "\".\"" + meataData.uuid() + "\"  limit 2 OFFSET 0");
        final ResultSetMetaData metaData = resultSet.getMetaData();
        final int columnCount = metaData.getColumnCount();

        assertEquals(columnCount, 1);

        int resultsFound = 0;
        while (resultSet.next()) {
            assertEquals(metaData.getColumnName(1), "PAGE_ID");
            @SuppressWarnings("unchecked")
            List<Entry<Column, RecordValue<?>>> sValues = (List<Entry<Column, RecordValue<?>>>) resultSet
                    .getObject("PAGE_ID");
            assertEquals(sValues.size(), 1);
            RecordValue<?> onlyValue = sValues.iterator().next().getValue();
            assertEquals(onlyValue.visibility().toString(), "[en]");

            assertEquals(onlyValue.value(), Integer.valueOf(resultsFound).toString());
            resultsFound++;

        }

        assertEquals(resultsFound, 2);
    } finally {
        close(connection, statement);
    }
}

From source file:cosmos.sql.TestSql.java

@Test
public void testJoin() throws SQLException {
    loadDriverClass();/*from   ww w .java 2 s .co m*/
    Connection connection = null;
    Statement statement = null;
    try {
        Properties info = new Properties();
        info.put("url", JDBC_URL);
        info.put("user", USER);
        info.put("password", PASSWORD);
        connection = DriverManager.getConnection("jdbc:accumulo:cosmos//localhost", info);
        statement = connection.createStatement();
        final ResultSet resultSet = statement.executeQuery("select \"PAGE_ID\" from \"" + CosmosDriver.COSMOS
                + "\".\"" + meataData.uuid() + "\"  limit 2 OFFSET 0");
        final ResultSetMetaData metaData = resultSet.getMetaData();
        final int columnCount = metaData.getColumnCount();

        assertEquals(columnCount, 1);

        int resultsFound = 0;
        while (resultSet.next()) {
            assertEquals(metaData.getColumnName(1), "PAGE_ID");
            @SuppressWarnings("unchecked")
            List<Entry<Column, RecordValue<?>>> sValues = (List<Entry<Column, RecordValue<?>>>) resultSet
                    .getObject("PAGE_ID");
            assertEquals(sValues.size(), 1);
            RecordValue<?> onlyValue = sValues.iterator().next().getValue();
            assertEquals(onlyValue.visibility().toString(), "[en]");

            assertEquals(onlyValue.value(), Integer.valueOf(resultsFound).toString());
            resultsFound++;

        }

        assertEquals(resultsFound, 2);
    } finally {
        close(connection, statement);
    }
}