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.calcite.test.CalciteAssert.java

private static String typeString(ResultSetMetaData metaData) throws SQLException {
    final List<String> list = new ArrayList<>();
    for (int i = 0; i < metaData.getColumnCount(); i++) {
        list.add(metaData.getColumnName(i + 1) + " " + metaData.getColumnTypeName(i + 1)
                + (metaData.isNullable(i + 1) == ResultSetMetaData.columnNoNulls ? " NOT NULL" : ""));
    }/*from   www .j  a  v  a 2  s. c  om*/
    return list.toString();
}

From source file:com.iih5.smartorm.model.DbExecutor.java

/**
 * Model/*from   ww  w.j a v  a2s. co m*/
 * @param sql
 * @param paras
 * @param model
 * @param <T>
 * @return
 * @
 */
<T> List<T> queryList(String sql, Object[] paras, final Class<T> model) {
    final Set<String> columnMeta = new HashSet<String>();
    return jdbc.query(sql, paras, new RowMapper<T>() {
        public T mapRow(ResultSet rs, int rowNum) throws SQLException {
            try {
                if (columnMeta.size() == 0) {
                    for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
                        String column = rs.getMetaData().getColumnLabel(i + 1);
                        columnMeta.add(column);
                    }
                }
                Model mModel = (Model) model.newInstance();
                Field[] fields = mModel.getClass().getFields();
                if (0 < fields.length) {
                    for (Field f : fields) {
                        if (columnMeta.contains(f.getName())) {
                            f.set(mModel, rs.getObject(f.getName()));
                        }
                    }
                } else {
                    ResultSetMetaData rad = rs.getMetaData();
                    int columnCount = rad.getColumnCount();
                    Map<String, Object> attrs = mModel.getAttrs();
                    for (int i = 1; i <= columnCount; i++) {
                        Object value = rs.getObject(i);
                        attrs.put(rad.getColumnName(i), value);
                    }
                }
                return (T) mModel;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    });
}

From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java

protected Integer searchColumnByName(String name) throws SQLException {
    Integer columnIndex = null;/*from   w w  w  .  j  ava2 s  .co m*/
    ResultSetMetaData metadata = resultSet.getMetaData();
    for (int i = 1; i <= metadata.getColumnCount(); i++) {
        String columnName = metadata.getColumnName(i);
        if (name.equalsIgnoreCase(columnName)) {
            columnIndex = i;
            break;
        }
    }
    return columnIndex;
}

From source file:org.apache.syncope.core.util.ImportExport.java

private void doExportTable(final TransformerHandler handler, final Connection conn, final String tableName)
        throws SQLException, SAXException {

    AttributesImpl attrs = new AttributesImpl();

    PreparedStatement stmt = null;
    ResultSet rs = null;//from w w w.j  a v  a  2  s. co  m
    ResultSet pkeyRS = null;

    try {
        // ------------------------------------
        // retrieve primary keys to perform an ordered select

        final DatabaseMetaData meta = conn.getMetaData();
        pkeyRS = meta.getPrimaryKeys(null, null, tableName);

        final StringBuilder orderBy = new StringBuilder();

        while (pkeyRS.next()) {
            final String columnName = pkeyRS.getString("COLUMN_NAME");

            if (columnName != null) {
                if (orderBy.length() > 0) {
                    orderBy.append(",");
                }

                orderBy.append(columnName);
            }
        }

        // ------------------------------------
        stmt = conn.prepareStatement(
                "SELECT * FROM " + tableName + " a" + (orderBy.length() > 0 ? " ORDER BY " + orderBy : ""));

        rs = stmt.executeQuery();
        for (int rowNo = 0; rs.next(); rowNo++) {
            attrs.clear();

            final ResultSetMetaData rsMeta = rs.getMetaData();

            for (int i = 0; i < rsMeta.getColumnCount(); i++) {
                final String columnName = rsMeta.getColumnName(i + 1);
                final Integer columnType = rsMeta.getColumnType(i + 1);

                // Retrieve value taking care of binary values.
                String value = getValues(rs, columnName, columnType);

                if (value != null) {
                    attrs.addAttribute("", "", columnName, "CDATA", value);
                }
            }

            handler.startElement("", "", tableName, attrs);
            handler.endElement("", "", tableName);
        }
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        if (pkeyRS != null) {
            try {
                pkeyRS.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
    }
}

From source file:net.certifi.audittablegen.PostgresqlDMR.java

/**
 * Get List of ColumnDef objects for all tables
 * in the targeted database/schema.  Postgres specific code replaces 
 * 'serial' date type with integer, because the column in the audit table
 * must be of type integer and not serial.  Since this data is interpreted
 * by ChangeSourceFactory, which should be database independent, the
 * translation needs to be in the DMR.//from w w  w  .  j  a va2s .c  o m
 * 
 * @param tableName
 * @return ArrayList of ColumnDef objects or an empty list if none are found.
 */
@Override
public List getColumns(String tableName) {

    //getDataTypes will initialize the map if it isn't already loaded
    Map<String, DataTypeDef> dtds = getDataTypes();

    List columns = new ArrayList<>();

    try {
        Connection conn = dataSource.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        ResultSet rs = dmd.getColumns(null, verifiedSchema, tableName, null);

        //load all of the metadata in the result set into a map for each column

        ResultSetMetaData rsmd = rs.getMetaData();
        int metaDataColumnCount = rsmd.getColumnCount();
        if (!rs.isBeforeFirst()) {
            throw new RuntimeException(
                    "No results for DatabaseMetaData.getColumns(" + verifiedSchema + "." + tableName + ")");
        }
        while (rs.next()) {
            ColumnDef columnDef = new ColumnDef();
            Map columnMetaData = new CaseInsensitiveMap();
            for (int i = 1; i <= metaDataColumnCount; i++) {
                columnMetaData.put(rsmd.getColumnName(i), rs.getString(i));
            }
            columnDef.setName(rs.getString("COLUMN_NAME"));

            String type_name = rs.getString("TYPE_NAME");
            if (type_name.equalsIgnoreCase("serial")) {
                columnDef.setTypeName("int4");
            } else {
                columnDef.setTypeName(type_name);
            }
            columnDef.setSqlType(rs.getInt("DATA_TYPE"));
            columnDef.setSize(rs.getInt("COLUMN_SIZE"));
            columnDef.setDecimalSize(rs.getInt("DECIMAL_DIGITS"));
            columnDef.setSourceMeta(columnMetaData);

            if (dtds.containsKey(columnDef.getTypeName())) {
                columnDef.setDataTypeDef(dtds.get(columnDef.getTypeName()));
            } else {
                throw new RuntimeException(
                        "Missing DATA_TYPE definition for data type " + columnDef.getTypeName());
            }
            columns.add(columnDef);
        }

    } catch (SQLException e) {
        throw Throwables.propagate(e);
    }

    return columns;

}

From source file:com.streamsets.pipeline.stage.processor.parser.sql.SqlParserProcessor.java

private void resolveSchema(SchemaAndTable schemaAndTable) throws StageException {
    Map<String, Integer> columns = new HashMap<>();
    String schema = schemaAndTable.getSchema();
    String table = schemaAndTable.getTable();
    try (Statement s = connection.createStatement()) {
        ResultSetMetaData md = s
                .executeQuery(Utils.format("SELECT * FROM {}{} WHERE 1 = 0",
                        StringUtils.isNotEmpty(schema) ? "\"" + schema + "\"." : "", "\"" + table + "\""))
                .getMetaData();//  www  . j  ava  2 s  . c o m
        int colCount = md.getColumnCount();
        for (int i = 1; i <= colCount; i++) {
            int colType = md.getColumnType(i);
            String colName = md.getColumnName(i);
            if (!configBean.caseSensitive) {
                colName = colName.toUpperCase();
            }
            if (colType == Types.DATE || colType == Types.TIME || colType == Types.TIMESTAMP) {
                dateTimeColumns.computeIfAbsent(schemaAndTable, k -> new HashMap<>());
                dateTimeColumns.get(schemaAndTable).put(colName, md.getColumnTypeName(i));
            }

            if (colType == Types.DECIMAL || colType == Types.NUMERIC) {
                decimalColumns.computeIfAbsent(schemaAndTable, k -> new HashMap<>()).put(colName,
                        new PrecisionAndScale(md.getPrecision(i), md.getScale(i)));
            }
            columns.put(md.getColumnName(i), md.getColumnType(i));
        }
        tableSchemas.put(schemaAndTable, columns);
    } catch (SQLException ex) {
        throw new StageException(JDBC_00, configBean.hikariConfigBean.connectionString);
    }
}

From source file:cn.labthink.ReadAccess060.java

private void generateCellData(Integer testID, int cellno) throws SQLException {
    Vector columns = null;//from   w  w w  .j a v a  2s . c  o m
    Vector data = null;

    data = new Vector();
    columns = new Vector();

    //                PreparedStatement st = con.prepareStatement("SELECT * FROM RESULTS WHERE TESTID = ? AND CELLID = ? ORDER BY RESULTID");
    PreparedStatement st = conn.prepareStatement(
            "SELECT TESTTEMPERATURE,HUMIDITY,WEIGHT,AMBTEMP,PRODUCETIME,AREA,THICKNESS  FROM RESULTS WHERE TESTID = ? AND CELLID = ? ORDER BY RESULTID");
    st.setInt(1, testID);
    st.setObject(2, cellno);

    rs = st.executeQuery();

    ResultSetMetaData md = rs.getMetaData();
    int columnCount = md.getColumnCount();
    //store column names 
    for (int i = 1; i <= columnCount; i++) {
        columns.add(md.getColumnName(i));
        //                System.out.println(md.getColumnName(i));
    }
    columns.ensureCapacity(columnCount);

    Vector row;
    while (rs.next()) {

        row = new Vector(columnCount);
        for (int i = 1; i <= columnCount; i++) {
            row.add(rs.getString(i));
            //                    System.out.print(rs.getString(i));
            //                    System.out.print(",");
        }
        //                System.out.print("\r\n");
        data.add(row);

        //Debugging    
    }

    outputexcelCell(columns, data, cellno);
}

From source file:cn.labthink.ReadAccess330.java

private void generateCellData(Integer testID, int cellno) throws SQLException {
    Vector columns = null;/*from w ww  .  j av  a2s.  c  o  m*/
    Vector data = null;

    data = new Vector();
    columns = new Vector();

    //                PreparedStatement st = con.prepareStatement("SELECT * FROM RESULTS WHERE TESTID = ? AND CELLID = ? ORDER BY RESULTID");
    PreparedStatement st = conn.prepareStatement(
            "SELECT TIMESPAN,TESTTEMPERATURE,ABOVEHUMIDITY,BELOWHUMIDITY,ABOVEPRESSURE,BELOWPRESSURE,FLOWRATE,OPPM,WPPM,OTR,WVTR,SENSORTEMP,AMBTEMP,TESTTYPE,AMTEMPERATURE,AMHUMIDITY,PRODUCETIME,COFFICIENT  FROM RESULTS WHERE TESTID = ? AND CELLID = ? ORDER BY RESULTID");
    st.setInt(1, testID);
    st.setObject(2, cellno);

    rs = st.executeQuery();

    ResultSetMetaData md = rs.getMetaData();
    int columnCount = md.getColumnCount();
    //store column names 
    for (int i = 1; i <= columnCount; i++) {
        columns.add(md.getColumnName(i));
        //                System.out.println(md.getColumnName(i));
    }
    columns.ensureCapacity(columnCount);

    Vector row;
    while (rs.next()) {

        row = new Vector(columnCount);
        for (int i = 1; i <= columnCount; i++) {
            row.add(rs.getString(i));
            //                    System.out.print(rs.getString(i));
            //                    System.out.print(",");
        }
        //                System.out.print("\r\n");
        data.add(row);

        //Debugging    
    }

    outputexcelCell(columns, data, cellno);
}

From source file:com.tonbeller.jpivot.mondrian.ScriptableMondrianDrillThroughTableModel.java

/**
 * execute sql query/* w  ww . ja  va 2s. co  m*/
 * @throws Exception
 */
private void executeQuery() {
    Connection con = null;
    try {
        InputStream catExtIs = ScriptableMondrianDrillThroughTableModel.class.getClassLoader()
                .getResourceAsStream("/" + catalogExtension);
        Digester catExtDigester = new Digester();
        catExtDigester.push(this);
        catExtDigester.addSetProperties("extension");
        catExtDigester.addObjectCreate("extension/script", "com.tonbeller.jpivot.mondrian.script.ScriptColumn");
        catExtDigester.addSetProperties("extension/script");
        catExtDigester.addSetNext("extension/script", "addScript");
        catExtDigester.parse(catExtIs);

        URL scriptsBaseURL = Thread.currentThread().getContextClassLoader().getResource(scriptRootUrl);
        scriptEngine = new GroovyScriptEngine(new URL[] { scriptsBaseURL });

        con = getConnection();
        Statement s = con.createStatement();
        s.setMaxRows(maxResults);
        ResultSet rs = s.executeQuery(sql);
        ResultSetMetaData md = rs.getMetaData();
        int numCols = md.getColumnCount();
        List columnTitlesList = new ArrayList();
        // set column headings
        for (int i = 0; i < numCols; i++) {
            //   columns are 1 based
            columnTitlesList.add(i, md.getColumnName(i + 1));
        }
        // loop on script columns
        for (ListIterator sIt = scripts.listIterator(); sIt.hasNext();) {
            final ScriptColumn sc = (ScriptColumn) sIt.next();
            columnTitlesList.add(sc.getPosition() - 1, sc.getTitle());
        }
        columnTitles = (String[]) columnTitlesList.toArray(new String[0]);
        // loop through rows
        List tempRows = new ArrayList();
        Map scriptInput = new HashMap();
        Binding binding = new Binding();
        while (rs.next()) {
            List rowList = new ArrayList();
            scriptInput.clear();
            // loop on columns, 1 based
            for (int i = 0; i < numCols; i++) {
                rowList.add(i, rs.getObject(i + 1));
                scriptInput.put(columnTitles[i], rs.getObject(i + 1));
            }
            binding.setVariable("input", scriptInput);
            // loop on script columns
            for (ListIterator sIt = scripts.listIterator(); sIt.hasNext();) {
                final ScriptColumn sc = (ScriptColumn) sIt.next();
                scriptEngine.run(sc.getFile(), binding);
                final Object output = binding.getVariable("output");
                if (output instanceof Map) {
                    Map outMap = (Map) output;
                    rowList.add(sc.getPosition() - 1,
                            new DefaultCell((String) outMap.get("URL"), (String) outMap.get("Value")));
                } else if (output instanceof String) {
                    rowList.add(sc.getPosition() - 1, (String) output);
                } else {
                    throw new Exception("Unknown groovy script return type (not a Map nor String).");
                }
            }
            tempRows.add(new DefaultTableRow(rowList.toArray()));
        }
        rs.close();
        rows = (TableRow[]) tempRows.toArray(new TableRow[0]);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("?", e);
        // problem occured, set table model to zero size
        rows = new TableRow[1];
        columnTitles = new String[1];
        columnTitles[0] = "An error occured";
        Object[] row = new Object[1];
        row[0] = e.toString();
        rows[0] = new DefaultTableRow(row);
        ready = false;
        return;
    } finally {
        try {
            con.close();
        } catch (Exception e1) {
            // ignore
        }
    }
    ready = true;
}

From source file:herddb.cli.HerdDBCLI.java

private static ExecuteStatementResult reallyExecuteStatement(final Statement statement, boolean resultSet,
        boolean verbose, boolean getResults, boolean prettyPrint) throws SQLException {

    if (resultSet) {
        try (ResultSet rs = statement.getResultSet()) {
            List<Map<String, Object>> results = new ArrayList<>();
            TextTableBuilder tb = new TextTableBuilder();

            ResultSetMetaData md = rs.getMetaData();
            List<String> columns = new ArrayList<>();
            int ccount = md.getColumnCount();
            for (int i = 1; i <= ccount; i++) {
                columns.add(md.getColumnName(i));
            }//from www.ja  v  a2  s . com

            if (!getResults) {
                if (prettyPrint) {
                    tb.addIntestation(columns);
                } else {
                    System.out.println(columns.stream().collect(Collectors.joining(";")));
                }
            }

            while (rs.next()) {
                List<String> values = new ArrayList<>();
                for (int i = 1; i <= ccount; i++) {
                    String value = rs.getString(i);
                    if (value == null) {
                        value = "<NULL>";
                    }
                    values.add(value);
                }

                if (getResults) {
                    Map<String, Object> row = new LinkedHashMap<>(); // Preserving order
                    int i = 0;
                    for (String col : columns) {
                        row.put(col, values.get(i++));
                    }
                    results.add(row);
                } else {
                    if (prettyPrint) {
                        tb.addRow(values);
                    } else {
                        System.out.println(values.stream().collect(Collectors.joining(";")));
                    }
                }
            }

            if (getResults) {
                return new ExecuteStatementResult(results);
            }
            if (prettyPrint) {
                System.out.println("\n" + tb.toString());
            }
            return null;
        }
    } else {
        int updateCount = statement.getUpdateCount();
        if (verbose) {
            System.out.println("UPDATE COUNT: " + updateCount);
        }
        return new ExecuteStatementResult(updateCount >= 0 ? updateCount : 0);
    }
}