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:fr.bird.bloom.model.DatabaseTreatment.java

/**
 * Format request result/*from   w w  w.  ja v a2s  . c  om*/
 * 
 * @param resultMeta
 * @throws SQLException
 * @return void
 */
public void setResultatSelect(ResultSetMetaData resultMeta) throws SQLException {
    resultatSelect = new ArrayList<>();

    String firstLine = "";
    for (int i = 1; i <= resultMeta.getColumnCount(); i++) {
        firstLine += resultMeta.getColumnName(i) + ",";
    }
    firstLine = firstLine.substring(0, firstLine.length() - 1);
    resultatSelect.add(firstLine);

    while (resultSet.next()) {
        String line = "";
        for (int i = 1; i <= resultMeta.getColumnCount(); i++) {

            try {
                //System.out.print(resultSet.getObject(i) + "\t");
                line += "\"" + resultSet.getObject(i) + "\"" + ",";
            } catch (Exception e) {
                line += "\"\",";
            }

        }
        line = line.substring(0, line.length() - 1);
        //System.out.println(line);
        resultatSelect.add(line);
    }
}

From source file:com.micromux.cassandra.jdbc.MetadataResultSetsTest.java

private String getColumnNames(ResultSetMetaData metaData) throws SQLException {
    StringBuilder sb = new StringBuilder();
    int count = metaData.getColumnCount();
    for (int i = 1; i <= count; i++) {
        sb.append(metaData.getColumnName(i));
        if (i < count)
            sb.append(", ");
    }//from ww  w .  ja va  2  s  . c  om
    return sb.toString();
}

From source file:com.abixen.platform.service.businessintelligence.multivisualisation.application.service.database.AbstractDatabaseService.java

private DataSourceColumn prepareDataSourceColumns(ResultSetMetaData rsmd, int i) throws SQLException {
    DataValueType dataValueType = DataValueType.valueOf(getValidColumnTypeName(i, rsmd));
    String name = rsmd.getColumnName(i);
    return DataSourceColumn.builder().details(name).parameters(dataValueType, i).build();
}

From source file:com.novartis.opensource.yada.format.ResultSetResultDelimitedConverter.java

/**
 * Converts columns of data in a {@link java.sql.ResultSet} to collection
 * of {@link List} objects containing values and stored in the current
 * {@link YADAQueryResult#getConvertedResults()} structure.
 * /* w w  w.j ava  2 s  . c o  m*/
 * @param rs
 *          the result set to convert
 * @throws SQLException
 *           when {@link ResultSet} or {@link ResultSetMetaData} iteration
 *           fails
 */
protected void getDelimitedRows(ResultSet rs) throws SQLException {
    JSONObject h = (JSONObject) this.harmonyMap;
    ResultSetMetaData rsmd = rs.getMetaData();
    if (rsmd == null) // TODO What happens to headers when rsmd is null, or
                      // resultSet is empty?
        rsmd = new RowSetMetaDataImpl();
    int colCount = rsmd.getColumnCount();
    boolean hasYadaRnum = rsmd.getColumnName(colCount).toLowerCase().equals(JDBCAdaptor.ROWNUM_ALIAS);

    // handle headers
    // TODO How to suppress headers?
    for (int j = 1; j <= colCount; j++) {
        String colName = rsmd.getColumnName(j);
        if (!hasYadaRnum || !colName.toLowerCase().equals(JDBCAdaptor.ROWNUM_ALIAS)) {
            String col = colName;
            if (isHarmonized()) {
                if (h.has(colName)) {
                    col = h.getString(colName);
                }
            }
            getYADAQueryResult().addConvertedHeader(this.wrap(col));
        }
    }
    List<List<String>> convertedResult = new ArrayList<>();
    while (rs.next()) {
        List<String> resultsRow = new ArrayList<>();
        String colValue;
        for (int j = 1; j <= colCount; j++) {
            String colName = rsmd.getColumnName(j);
            if (!hasYadaRnum || !colName.toLowerCase().equals(JDBCAdaptor.ROWNUM_ALIAS)) {
                if (null == rs.getString(colName) || "null".equals(rs.getString(colName))) {
                    colValue = NULL_REPLACEMENT;
                } else {
                    colValue = this.wrap(rs.getString(colName));
                }
                resultsRow.add(colValue);
            }
        }
        convertedResult.add(resultsRow);
    }
    getYADAQueryResult().getConvertedResults().add(convertedResult);
}

From source file:gridool.util.csv.CsvWriter.java

private void writeColumnNames(final ResultSetMetaData metadata) throws SQLException {
    final int numColumns = metadata.getColumnCount();
    for (int i = 1; i <= numColumns; i++) {
        if (i != 1) {
            write(separator);/*from w  w w  .ja v  a  2  s  . c om*/
        }
        String columnName = metadata.getColumnName(i);
        write(columnName);
    }
    write(lineSeparator);
}

From source file:RawSQLServlet.java

/** Do the SQL query */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String query = request.getParameter("sql");

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    if (query == null) {
        out.println("<b>Error: malformed query, contact administrator</b>");
        return;//from  w ww  .  j  a v  a 2 s  .  c  o m
    }

    // NB MUST also check for admin privs before proceding!

    try { // SQL
        out.println("<p>Your query: <b>" + query + "</b></p>");
        stmt.execute(query);
        ResultSet rs = stmt.getResultSet();
        if (rs == null) {
            // print updatecount
            out.println("<p>Result: updateCount = <b>" + stmt.getUpdateCount() + "</p>");
        } else {
            // process resultset

            out.println("<br>Your response:");

            ResultSetMetaData md = rs.getMetaData();
            int count = md.getColumnCount();
            out.println("<table border=1>");
            out.print("<tr>");
            for (int i = 1; i <= count; i++) {
                out.print("<th>");
                out.print(md.getColumnName(i));
            }
            out.println("</tr>");
            while (rs.next()) {
                out.print("<tr>");
                for (int i = 1; i <= count; i++) {
                    out.print("<td>");
                    out.print(rs.getString(i));
                }
                out.println("</tr>");
            }
        }
        out.println("</table>");
        // rs.close();
    } catch (SQLException ex) {
        out.print("<B>" + getClass() + ": SQL Error:</B>\n" + ex);
        out.print("<pre>");
        ex.printStackTrace(out);
        out.print("</pre>");
    }
}

From source file:user.Query.java

public CategoryDataset getWeatherAndTweets() {
    query = " SELECT (Select COUNT(*)" + " FROM TWEET, WEATHER" + " WHERE WEATHER.RAIN = 'false' "
            + " AND WEATHER.SNOW = 'false' " + " AND TWEET.DATE = WEATHER.DATE ) as \"Amount good weather\""
            + " ," + " (SELECT COUNT(*) " + " FROM TWEET, WEATHER" + " WHERE WEATHER.RAIN =  'true'"
            + " AND TWEET.DATE = WEATHER.DATE ) as \"Amount bad weather\"" + "  FROM tweet, weather"
            + " Where tweet." + time.substring(1) + " Group by \"Amount good weather\"; ";

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    try {/*from w ww . j  a  v  a 2  s  . c o  m*/
        ResultSet resultSet = executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();
        while (resultSet.next()) {
            int count = metaData.getColumnCount();
            for (int i = 1; i <= count; i++) {
                dataset.addValue(Integer.parseInt(resultSet.getString(i)), "Tweets", metaData.getColumnName(i));
            }
        }
    } catch (SQLException ex) {
    }
    return dataset;
}

From source file:com.novartis.opensource.yada.format.ResultSetResultXMLConverter.java

/**
 * Constructs an xml fragment of {@code ROW} elements with the result set data
 * @param rs the result set containing the data to be converted
 * @return a {@link DocumentFragment} containing the result data wrapped in XML
 * @throws SQLException when {@code rs} cannot be iterated or accessed
 *//*from ww  w  . j a  v a 2  s  .c om*/
private DocumentFragment getXMLRows(ResultSet rs) throws SQLException {
    DocumentFragment rows = this.doc.createDocumentFragment();

    ResultSetMetaData rsmd = rs.getMetaData();
    if (rsmd == null)
        rsmd = new RowSetMetaDataImpl();
    while (rs.next()) {
        Element row = this.doc.createElement(ROW);
        String colValue;
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String colName = rsmd.getColumnName(i);
            if (!colName.toLowerCase().equals(JDBCAdaptor.ROWNUM_ALIAS)) {
                String col = isHarmonized() && ((JSONObject) this.harmonyMap).has(colName)
                        ? ((JSONObject) this.harmonyMap).getString(colName)
                        : colName;
                if (null == rs.getString(colName) || NULL.equals(rs.getString(colName))) {
                    colValue = NULL_REPLACEMENT;
                } else {
                    colValue = rs.getString(colName);
                }
                Element column = this.doc.createElement(col);
                Text value = this.doc.createTextNode(colValue);
                column.appendChild(value);
                row.appendChild(column);
            }
        }
        rows.appendChild(row);
    }
    return rows;

}

From source file:com.adaptris.core.services.jdbc.JdbcDataCaptureServiceImpl.java

protected void saveKeys(AdaptrisMessage msg, Statement stmt) throws SQLException {
    ResultSet rs = null;/*from   w  w w.  j  a  va 2 s  .  c o m*/
    Statement savedKeysQuery = null;

    try {
        if (saveReturnedKeys()) {
            if (!actor.isOldJbc()) {
                rs = stmt.getGeneratedKeys();
                rs.next();
                ResultSetMetaData rsmd = rs.getMetaData();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    String name = rsmd.getColumnName(i);
                    String value = rs.getObject(name).toString();
                    msg.addMetadata(name, value);
                }
            } else {
                savedKeysQuery = createStatement(actor.getSqlConnection());
                rs = savedKeysQuery.executeQuery(
                        "select max(" + saveReturnedKeysColumn + ") from " + saveReturnedKeysTable + ";");
                rs.next();
                String value = rs.getObject(saveReturnedKeysColumn).toString();
                msg.addMetadata(saveReturnedKeysColumn, value);
            }
        }
    } finally {
        JdbcUtil.closeQuietly(savedKeysQuery);
        JdbcUtil.closeQuietly(rs);
    }
}

From source file:com.abixen.platform.module.chart.service.impl.AbstractDatabaseService.java

public List<String> getColumns(Connection connection, String tableName) {

    List<String> columns = new ArrayList<>();

    try {//from  ww  w. j a v a 2 s.c o m
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName);
        ResultSetMetaData rsmd = rs.getMetaData();

        int columnCount = rsmd.getColumnCount();

        IntStream.range(1, columnCount + 1).forEach(i -> {
            try {
                columns.add(rsmd.getColumnName(i));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return columns;
}