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:cosmos.sql.TestSql.java

@Test
public void testDisjunctionPositive() throws SQLException {
    loadDriverClass();/*from  w w w. j a v a2  s.  c  om*/
    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() + "\"  where PAGE_ID='9' or REVISION_ID='8'");
        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]");

            assertTrue(onlyValue.value().equals(Integer.valueOf(9).toString())
                    || onlyValue.value().equals(Integer.valueOf(8).toString()));
            resultsFound++;

        }

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

From source file:cosmos.sql.TestSql.java

@Test
public void testConjunction() throws SQLException {
    loadDriverClass();/*from w  w  w  .  j a v a2  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() + "\"  where PAGE_ID='9' and REVISION_ID='9'");
        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(9).toString());
            resultsFound++;
            break;

        }

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

From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.ExtendedRowSetBuilder.java

private void buildFormatterAndNamesArray(ResultSetMetaData rsm,
        Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter)
        throws Exception {
    fFormatters = new FieldFormatter[rsm.getColumnCount() + 1];
    colNames = new String[rsm.getColumnCount() + 1];

    for (int i = 1; i < fFormatters.length; i++) {
        String cName = rsm.getColumnLabel(i);
        if (cName == null) {
            cName = rsm.getColumnName(i);
        }//from   w  w  w.  j av  a 2  s  . c om
        colNames[i] = adaptName(cName);
        FieldFormatter fF = fieldNameToFormatter.get(cName);
        if (fF == null) {
            fF = fieldIdToFormatter.get("" + i);
        }
        fFormatters[i] = fF;
    }
}

From source file:com.serphacker.serposcope.db.base.ExportDB.java

public boolean export(Writer writer) throws IOException {
    for (String resource : MigrationDB.DB_SCHEMA_FILES) {
        String sql = new String(ByteStreams.toByteArray(MigrationDB.class.getResourceAsStream(resource)));
        sql = sql.replaceAll("--.*\n", "\n");
        sql = sql.replaceAll("\\s+", " ");
        sql = sql.replaceAll(";\\s*", ";\n");
        writer.append(sql);/*from ww w.j  ava 2 s  .c o m*/
        writer.append("\n");
    }

    writer.append("\nSET FOREIGN_KEY_CHECKS=0;\n");
    try (Connection con = ds.getConnection()) {
        for (String table : TABLES) {
            writer.flush();
            try (Statement stmt = con.createStatement()) {
                LOG.info("exporting table {}", table);
                long _start = System.currentTimeMillis();

                stmt.setQueryTimeout(3600 * 24);
                ResultSet rs = stmt.executeQuery("SELECT * FROM `" + table + "`");
                ResultSetMetaData metaData = rs.getMetaData();
                int columns = metaData.getColumnCount();

                String insertStatement = "INSERT INTO `" + table + "` VALUES ";

                StringBuilder stmtBuilder = new StringBuilder(insertStatement);
                while (rs.next()) {

                    StringBuilder entryBuilder = new StringBuilder("(");
                    for (int colIndex = 1; colIndex <= columns; colIndex++) {
                        Object object = rs.getObject(colIndex);
                        String colName = metaData.getColumnName(colIndex);
                        String colClassName = metaData.getColumnClassName(colIndex);
                        String escaped = escape(object, colClassName, colName);
                        entryBuilder.append(escaped);
                        if (colIndex < columns) {
                            entryBuilder.append(',');
                        }
                    }
                    entryBuilder.append("),");

                    if (stmtBuilder.length() != insertStatement.length()
                            && stmtBuilder.length() + entryBuilder.length() > DEFAULT_MAX_ALLOWED_PACKET) {
                        stmtBuilder.setCharAt(stmtBuilder.length() - 1, ';');
                        writer.append(stmtBuilder).append('\n');
                        stmtBuilder = new StringBuilder(insertStatement);
                    }

                    stmtBuilder.append(entryBuilder);
                }

                if (stmtBuilder.length() != insertStatement.length()) {
                    stmtBuilder.setCharAt(stmtBuilder.length() - 1, ';');
                    writer.append(stmtBuilder).append('\n');
                }

                LOG.info("exported table {} in {}", table,
                        DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - _start));
            }
        }
        writer.append("SET FOREIGN_KEY_CHECKS=1;\n");
    } catch (Exception ex) {
        LOG.error("SQL error", ex);
        return false;
    }

    return true;
}

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

@Test
public void testCreateSchemaNoTableName() throws ClassNotFoundException, SQLException {

    final ResultSet resultSet = mock(ResultSet.class);
    final ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class);
    when(resultSet.getMetaData()).thenReturn(resultSetMetaData);
    when(resultSetMetaData.getColumnCount()).thenReturn(1);
    when(resultSetMetaData.getTableName(1)).thenReturn("");
    when(resultSetMetaData.getColumnType(1)).thenReturn(Types.INTEGER);
    when(resultSetMetaData.getColumnName(1)).thenReturn("ID");

    final Schema schema = JdbcCommon.createSchema(resultSet);
    assertNotNull(schema);/*from w w w .  j a v a 2  s  .com*/

    // records name, should be result set first column table name
    assertEquals("NiFi_ExecuteSQL_Record", schema.getName());

}

From source file:com.icsshs.datatransfer.database.impl.QueryBeanProcessor.java

/**
 * The positions in the returned array represent column numbers.  The
 * values stored at each position represent the index in the
 * <code>PropertyDescriptor[]</code> for the bean property that matches
 * the column name.  If no bean property was found for a column, the
 * position is set to <code>PROPERTY_NOT_FOUND</code>.
 *
 * @param rsmd The <code>ResultSetMetaData</code> containing column
 * information./*from ww w  .  j  a  v  a  2 s. co m*/
 *
 * @param props The bean property descriptors.
 *
 * @throws SQLException if a database access error occurs
 *
 * @return An int[] with column index to property index mappings.  The 0th
 * element is meaningless because JDBC column indexing starts at 1.
 */
protected int[] mapColumnsToProperties(ResultSetMetaData rsmd, PropertyDescriptor[] props) throws SQLException {

    int cols = rsmd.getColumnCount();
    int[] columnToProperty = new int[cols + 1];
    Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);

    for (int col = 1; col <= cols; col++) {
        String columnName = rsmd.getColumnLabel(col);
        if (null == columnName || 0 == columnName.length()) {
            columnName = rsmd.getColumnName(col);
        }
        for (int i = 0; i < props.length; i++) {

            if (columnName.equalsIgnoreCase(StringHelper.toUnderscore(props[i].getName()))) {
                columnToProperty[col] = i;
                break;
            }
        }
    }

    return columnToProperty;
}

From source file:CSVWriter.java

public String[] getColumnNames(ResultSet rs) throws SQLException {
    List<String> names = new ArrayList<String>();
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
        names.add(metadata.getColumnName(i + 1));
    }/*from  ww  w.j a  v  a  2  s.co  m*/

    String[] nameArray = new String[names.size()];
    return names.toArray(nameArray);
}

From source file:org.apache.hadoop.hive.ql.dataToDB.BaseDBExternalDataLoad.java

public void initFields() {
    ResultSetMetaData rsm;
    try {/*from  w w w .j  a  v a 2 s . c o m*/
        rsm = getMetaData();

        Table t = config.getTable();
        int total = rsm.getColumnCount();
        List<FieldSchema> fss = t.getCols();
        for (int i = 1; i <= total; i++) {
            fields.put(fss.get(i - 1).getName(), rsm.getColumnName(i));
        }
    } catch (SemanticException e) {

    } catch (SQLException e) {

    }
}

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

@Test
public void testCreateSchemaOnlyColumnLabel() throws ClassNotFoundException, SQLException {

    final ResultSet resultSet = mock(ResultSet.class);
    final ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class);
    when(resultSet.getMetaData()).thenReturn(resultSetMetaData);
    when(resultSetMetaData.getColumnCount()).thenReturn(2);
    when(resultSetMetaData.getTableName(1)).thenReturn("TEST");
    when(resultSetMetaData.getColumnType(1)).thenReturn(Types.INTEGER);
    when(resultSetMetaData.getColumnName(1)).thenReturn("");
    when(resultSetMetaData.getColumnLabel(1)).thenReturn("ID");
    when(resultSetMetaData.getColumnType(2)).thenReturn(Types.VARCHAR);
    when(resultSetMetaData.getColumnName(2)).thenReturn("VCHARC");
    when(resultSetMetaData.getColumnLabel(2)).thenReturn("NOT_VCHARC");

    final Schema schema = JdbcCommon.createSchema(resultSet);
    assertNotNull(schema);/*w w  w.jav a  2  s .  c om*/

    assertNotNull(schema.getField("ID"));
    assertNotNull(schema.getField("NOT_VCHARC"));

    // records name, should be result set first column table name
    assertEquals("TEST", schema.getName());
}

From source file:at.ac.univie.isc.asio.engine.sql.WebRowSetWriter.java

private void columnDefinition(final int idx, final ResultSetMetaData context)
        throws XMLStreamException, SQLException {
    // @formatter:off
    xml.writeStartElement(WRS, "column-definition");
    tag("column-index", idx);
    tag("auto-increment", context.isAutoIncrement(idx));
    tag("case-sensitive", context.isCaseSensitive(idx));
    tag("currency", context.isCurrency(idx));
    tag("nullable", context.isNullable(idx));
    tag("signed", context.isSigned(idx));
    tag("searchable", context.isSearchable(idx));
    tag("column-display-size", context.getColumnDisplaySize(idx));
    tag("column-label", context.getColumnLabel(idx));
    tag("column-name", context.getColumnName(idx));
    tag("schema-name", context.getSchemaName(idx));
    tag("column-precision", context.getPrecision(idx));
    tag("column-scale", context.getScale(idx));
    tag("table-name", context.getTableName(idx));
    tag("catalog-name", context.getCatalogName(idx));
    tag("column-type", context.getColumnType(idx));
    tag("column-type-name", context.getColumnTypeName(idx));
    xml.writeEndElement();//ww  w.  j  a  va 2 s .  co  m
    // @formatter:on
}