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:org.apache.phoenix.end2end.QueryServerBasicsIT.java

@Test
public void testCatalogs() throws Exception {
    try (final Connection connection = DriverManager.getConnection(CONN_STRING)) {
        assertThat(connection.isClosed(), is(false));
        try (final ResultSet resultSet = connection.getMetaData().getCatalogs()) {
            final ResultSetMetaData metaData = resultSet.getMetaData();
            assertFalse("unexpected populated resultSet", resultSet.next());
            assertEquals(1, metaData.getColumnCount());
            assertEquals(TABLE_CAT, metaData.getColumnName(1));
        }/* w  w  w .  j  ava 2s.c o m*/
    }
}

From source file:db.migration.V055__UpdateECTS.java

private int getNextHibernateSequence(JdbcTemplate jdbcTemplate) {
    // Returns next global id
    List<Map> resultSet = jdbcTemplate.query("SELECT nextval('public.hibernate_sequence')",
            new RowMapper<Map>() {
                @Override//from   w w w . j  av a  2s  .  c  o m
                public Map mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Map r = new HashMap<String, Object>();

                    ResultSetMetaData metadata = rs.getMetaData();
                    for (int i = 1; i <= metadata.getColumnCount(); i++) {
                        String cname = metadata.getColumnName(i);
                        int ctype = metadata.getColumnType(i);

                        switch (ctype) {
                        case Types.BIGINT: // id
                            r.put(cname, rs.getInt(cname));
                            break;

                        default:
                            break;
                        }
                    }

                    return r;
                }
            });

    for (Map m : resultSet) {
        return (int) m.get("nextval");
    }
    return 0;
}

From source file:shell.framework.dao.support.ListExtractor4Map.java

public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnNum = rsmd.getColumnCount();
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    while (rs.next()) {
        Map<String, Object> map4Row = new HashMap<String, Object>();
        for (int i = 1; i <= columnNum; i++) {
            map4Row.put(rsmd.getColumnName(i), rs.getObject(i));
        }/*from www . j av a2 s.  c  o m*/
        result.add(map4Row);
    }
    return result;
}

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

@Test
public void testSchemas() throws Exception {
    try (final Connection connection = DriverManager.getConnection(CONN_STRING)) {
        assertThat(connection.isClosed(), is(false));
        try (final ResultSet resultSet = connection.getMetaData().getSchemas()) {
            final ResultSetMetaData metaData = resultSet.getMetaData();
            assertTrue("unexpected empty resultset", resultSet.next());
            assertEquals(2, metaData.getColumnCount());
            assertEquals(TABLE_SCHEM, metaData.getColumnName(1));
            assertEquals(TABLE_CATALOG, metaData.getColumnName(2));
            boolean containsSystem = false;
            do {/*from ww w. j a va 2s .  com*/
                if (resultSet.getString(1).equalsIgnoreCase(SYSTEM_SCHEMA_NAME))
                    containsSystem = true;
            } while (resultSet.next());
            assertTrue(format("should contain at least %s schema.", SYSTEM_SCHEMA_NAME), containsSystem);
        }
    }
}

From source file:org.apache.zeppelin.tajo.TajoInterpreter.java

private InterpreterResult executeSql(String sql) {
    try {//  ww  w  . ja va 2 s . c  om
        if (exceptionOnConnect != null) {
            return new InterpreterResult(Code.ERROR, exceptionOnConnect.getMessage());
        }
        statement = connection.createStatement();
        StringBuilder msg = null;
        if (StringUtils.containsIgnoreCase(sql, "EXPLAIN ")) {
            //return the explain as text, make this visual explain later
            msg = new StringBuilder();
        } else {
            msg = new StringBuilder("%table ");
        }

        ResultSet res = statement.executeQuery(sql);
        try {
            ResultSetMetaData md = res.getMetaData();
            for (int i = 1; i < md.getColumnCount() + 1; i++) {
                if (i == 1) {
                    msg.append(md.getColumnName(i));
                } else {
                    msg.append("\t" + md.getColumnName(i));
                }
            }
            msg.append("\n");
            while (res.next()) {
                for (int i = 1; i < md.getColumnCount() + 1; i++) {
                    msg.append(res.getString(i) + "\t");
                }
                msg.append("\n");
            }
        } finally {
            try {
                res.close();
                statement.close();
            } finally {
                statement = null;
            }
        }

        InterpreterResult interpreterResult = new InterpreterResult(Code.SUCCESS, msg.toString());
        return interpreterResult;
    } catch (SQLException ex) {
        logger.error("Can not run " + sql, ex);
        return new InterpreterResult(Code.ERROR, ex.getMessage());
    }
}

From source file:org.anyframe.iam.core.userdetails.jdbc.ExtUsersByUsernameMapping.java

/**
 * Save column name in member variable from ResultSetMetaData. 
 * /*ww  w  .  j  a  va 2s  .  com*/
 * @param rs
 *             ResultSet
 * @throws SQLException
 *             fail to save column name
 */
protected void setColumnNames(ResultSet rs) throws SQLException {
    ResultSetMetaData meta = rs.getMetaData();
    this.columnCount = meta.getColumnCount();
    columnNames = new String[columnCount];
    this.metaExists = true;

    for (int i = 0; i < columnCount; ++i) {
        columnNames[i] = meta.getColumnName(i + 1);
    }
}

From source file:net.sf.jdmf.data.sources.jdbc.JDBCDataSource.java

/**
 * @see net.sf.jdmf.data.sources.DataSource#getAttributes()
 *///from   w  ww. j  av a2 s. c  o  m
public Map<String, List<Comparable>> getAttributes() {
    Map<String, List<Comparable>> attributes = new LinkedHashMap<String, List<Comparable>>();

    try {
        Connection connection = DriverManager.getConnection(connectionString, userName, password);

        Statement statement = connection.createStatement();

        for (String query : queries) {
            ResultSet resultSet = statement.executeQuery(query);

            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            for (int i = 1; i <= columnCount; ++i) {
                String attributeName = metaData.getColumnName(i);
                List<Comparable> attributeValues = new ArrayList<Comparable>();

                attributes.put(attributeName, attributeValues);
            }

            while (resultSet.next()) {
                for (int i = 1; i <= columnCount; ++i) {
                    List<Comparable> attributeValues = attributes.get(metaData.getColumnName(i));

                    attributeValues.add(getValueAsComparable(resultSet.getObject(i)));
                }
            }

            resultSet.close();
        }

        statement.close();
        connection.close();
    } catch (SQLException e) {
        throw new DataSourceException("Could not retrieve data", e);
    }

    return attributes;
}

From source file:com.xtesoft.xtecuannet.framework.templater.filler.utils.SQLScanner.java

public List<SQLField> getSQLFields(String tableName) {
    List<SQLField> fields = new ArrayList<SQLField>(0);
    PreparedStatement psta = null;
    try {/*from www  .j ava 2  s . co m*/
        logger.info("Processing table: " + tableName);

        psta = getConnection().prepareStatement("select top 1 * from " + tableName);
        ResultSet rset = psta.executeQuery();
        ResultSetMetaData metadata = rset.getMetaData();
        int columnCount = metadata.getColumnCount();

        for (int i = 1; i <= columnCount; i++) {
            SQLField field = new SQLField(metadata.getColumnName(i), metadata.getColumnType(i));
            fields.add(field);
        }

        rset.close();
        psta.close();

    } catch (Exception e) {
        logger.error("Error getting fields for table: " + tableName, e);
    }

    return fields;
}

From source file:com.squid.kraken.v4.caching.redis.datastruct.RawMatrix.java

public static RawMatrix readExecutionItem(IExecutionItem item, long maxRecords)
        throws SQLException, ScopeException {
    long metter_start = System.currentTimeMillis();
    try {/*from  w w w .  j  av a 2  s.  co m*/
        RawMatrix matrix = new RawMatrix();
        ResultSet result = item.getResultSet();
        IJDBCDataFormatter formatter = item.getDataFormatter();
        //
        ResultSetMetaData metadata = result.getMetaData();
        int nbColumns = metadata.getColumnCount();

        IVendorSupport vendorSpecific;
        vendorSpecific = VendorSupportRegistry.INSTANCE.getVendorSupport(item.getDatabase());

        int[] normalizedTypes = vendorSpecific.getVendorMetadataSupport().normalizeColumnType(result);

        int i = 0;
        while (i < nbColumns) {
            matrix.colTypes.add(normalizedTypes[i]);
            matrix.colNames.add(metadata.getColumnName(i + 1));
            i++;
        }

        int count = 0;
        matrix.moreData = false;
        //
        while ((count++ < maxRecords || maxRecords < 0) && (matrix.moreData = result.next())) {
            Object[] rawrow = new Object[nbColumns];

            i = 0;
            while (i < nbColumns) {
                Object value = result.getObject(i + 1);
                Object unbox = formatter.unboxJDBCObject(value, matrix.colTypes.get(i));
                if (unbox instanceof String) {
                    String stringVal = (String) unbox;
                    rawrow[i] = DimensionValuesDictionary.INSTANCE.getRef(stringVal);
                } else {
                    rawrow[i] = unbox;
                }
                i++;
            }
            matrix.addRow(new RawRow(rawrow));
            count++;
        }
        long metter_finish = new Date().getTime();
        if (logger.isDebugEnabled()) {
            logger.debug(("SQLQuery#" + item.getID() + "read " + (count - 1) + " row(s) in "
                    + (metter_finish - metter_start) + " ms."));
        }
        return matrix;
    } finally {
        item.close();
    }
}

From source file:com.googlecode.datasourcetester.server.DataSourceTesterServiceImpl.java

public String[][] queryDataSource(String dataSourceJndiName, String query) {
    Connection conn = null;//from  w  w w. j a  v  a2s .  com
    try {
        InitialContext jndiContext = new InitialContext();
        DataSource ds = (DataSource) jndiContext.lookup(dataSourceJndiName);
        conn = ds.getConnection();
        PreparedStatement stmt = conn.prepareStatement(query);
        ResultSet rs = stmt.executeQuery();
        ResultSetMetaData resMeta = rs.getMetaData();
        LinkedList<String[]> rowList = new LinkedList<String[]>();
        String[] colLabels = new String[resMeta.getColumnCount()];
        for (int colNr = 1; colNr <= resMeta.getColumnCount(); colNr++) {
            colLabels[colNr - 1] = resMeta.getColumnName(colNr);
        }
        rowList.add(colLabels);
        while (rs.next()) {
            String[] rowData = new String[resMeta.getColumnCount()];
            for (int colNr = 1; colNr <= resMeta.getColumnCount(); colNr++) {
                rowData[colNr - 1] = rs.getString(colNr);
            }
            rowList.add(rowData);
        }
        conn.close();
        return rowList.toArray(new String[rowList.size()][]);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException sqlEx) {
            logger.error(sqlEx.getMessage(), sqlEx);
        }
        return null;
    }
}