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:com.ws.WS_TCS201.java

@Path("/GetTCD")
@JSONP(queryParam = "callback")
@GET/*w  w  w.j  a  v  a  2s . com*/
@Produces({ "application/x-javascript" })
public String GetTCD(@QueryParam("callback") String callback) {

    JSONObject obj1 = new JSONObject();
    LinkedList l1 = new LinkedList();
    //JSONArray l1 = new JSONArray();

    PreparedStatement prepStmt = null;

    try {
        String cSQL = "SELECT tcctcd,CONCAT(tcctcd,\" - \",trim(tcctxt)) AS name FROM TCSTCC "
                + "WHERE tcctcd NOT IN (\"A\",\"L\",\"N\",\"J\",\"R\",\"E\") " + "ORDER BY tcctcd ";
        prepStmt = connection.prepareStatement(cSQL);
        ResultSet result = prepStmt.executeQuery();
        ResultSetMetaData rsmd = result.getMetaData();
        int numcols = rsmd.getColumnCount();

        while (result.next()) {
            LinkedHashMap m1 = new LinkedHashMap();
            for (int j = 1; j <= numcols; j++) {
                Object obj = result.getObject(j);
                m1.put(rsmd.getColumnName(j).toString(), obj.toString());
            }
            l1.add(m1);
        }
        obj1.put("record", l1);
    } catch (SQLException e) {
        prepStmt = null;
        e.printStackTrace();
    } catch (Exception e) {
        prepStmt = null;
        e.printStackTrace();
    }
    return obj1.toString();
}

From source file:DbMetaServlet.java

private void printMeta(ResultSetMetaData metaData, String type, java.io.PrintWriter out, int colCount)
        throws SQLException {

    if (metaData == null || type == null || out == null)
        throw new IllegalArgumentException("Illegal args passed to printMeta()");

    out.println("<tr>");

    if (type.equals("table")) {

        out.println("<td><strong>Table name</strong></td>");

        for (int i = 1; i <= colCount; ++i) {

            out.println("<td>" + metaData.getTableName(i) + "</td>");
        }// w w  w.j a va2s. c om

    } else if (type.equals("name")) {

        out.println("<td><strong>Column name</strong></td>");

        for (int i = 1; i <= colCount; ++i) {

            out.println("<td>" + metaData.getColumnName(i) + "</td>");
        }

    } else if (type.equals("index")) {

        out.println("<td><strong>Column index</strong></td>");

        for (int i = 1; i <= colCount; ++i) {

            out.println("<td>" + i + "</td>");
        }

    } else if (type.equals("column type")) {

        out.println("<td><strong>Column type</strong></td>");

        for (int i = 1; i <= colCount; ++i) {

            out.println("<td>" + metaData.getColumnTypeName(i) + "</td>");
        }

    } else if (type.equals("column display")) {

        out.println("<td><strong>Column display size</strong></td>");

        for (int i = 1; i <= colCount; ++i) {

            out.println("<td>" + metaData.getColumnDisplaySize(i) + "</td>");
        }
    }

    out.println("</tr>");

}

From source file:com.ws.WS_TCS201.java

@Path("/GetID/{com}")
@JSONP(queryParam = "callback")
@GET/*w  w  w.  j a va 2 s .  c  o m*/
@Produces({ "application/x-javascript" })
public String GetID(@QueryParam("callback") String callback, @PathParam("com") String com) {
    //JOptionPane.showMessageDialog(null, "??", "Which way?", JOptionPane.INFORMATION_MESSAGE );
    JSONObject obj1 = new JSONObject();
    LinkedList l1 = new LinkedList();
    //JSONArray l1 = new JSONArray();

    PreparedStatement prepStmt = null;

    DateFormat day = new SimpleDateFormat("yyyyMMdd");
    String tmpday = day.format(new java.util.Date());

    try {
        String cSQL = "SELECT tceemp,tcenam FROM TCSTCE "
                + "WHERE tcecom = ? AND ( tceljd=0 OR tceljd + 100 > \"" + tmpday + "\" ) "
                + "ORDER BY tceemp,tcecom ";
        prepStmt = connection.prepareStatement(cSQL);
        prepStmt.setString(1, com);
        ResultSet result = prepStmt.executeQuery();
        ResultSetMetaData rsmd = result.getMetaData();
        int numcols = rsmd.getColumnCount();

        while (result.next()) {
            LinkedHashMap m1 = new LinkedHashMap();
            for (int j = 1; j <= numcols; j++) {
                Object obj = result.getObject(j);
                m1.put(rsmd.getColumnName(j).toString(), obj.toString());
            }
            l1.add(m1);
        }
        obj1.put("record", l1);
    } catch (SQLException e) {
        prepStmt = null;
        e.printStackTrace();
    } catch (Exception e) {
        prepStmt = null;
        e.printStackTrace();
    }
    return obj1.toString();
}

From source file:org.cloudgraph.rdb.filter.RDBStatementExecutor.java

@Override
public List<List<PropertyPair>> fetch(PlasmaType type, StringBuilder sql, Set<Property> props,
        Object[] params) {/*from w  w w.  java2  s .c  o m*/
    List<List<PropertyPair>> result = new ArrayList<List<PropertyPair>>();
    PreparedStatement statement = null;
    ResultSet rs = null;
    try {
        if (log.isDebugEnabled()) {
            if (params == null || params.length == 0) {
                log.debug("fetch: " + sql.toString());
            } else {
                StringBuilder paramBuf = new StringBuilder();
                paramBuf.append(" [");
                for (int p = 0; p < params.length; p++) {
                    if (p > 0)
                        paramBuf.append(", ");
                    paramBuf.append(String.valueOf(params[p]));
                }
                paramBuf.append("]");
                log.debug("fetch: " + sql.toString() + " " + paramBuf.toString());
            }
        }
        statement = con.prepareStatement(sql.toString(), ResultSet.TYPE_FORWARD_ONLY, /*
                                                                                       * ResultSet
                                                                                       * .
                                                                                       * TYPE_SCROLL_INSENSITIVE
                                                                                       * ,
                                                                                       */
                ResultSet.CONCUR_READ_ONLY);

        for (int i = 0; i < params.length; i++)
            statement.setString(i + 1, // FIXME
                    String.valueOf(params[i]));

        statement.execute();
        rs = statement.getResultSet();
        ResultSetMetaData rsMeta = rs.getMetaData();
        int numcols = rsMeta.getColumnCount();

        int count = 0;
        while (rs.next()) {
            List<PropertyPair> row = new ArrayList<PropertyPair>(numcols);
            result.add(row);
            for (int i = 1; i <= numcols; i++) {
                String columnName = rsMeta.getColumnName(i);
                int columnType = rsMeta.getColumnType(i);
                PlasmaProperty prop = (PlasmaProperty) type.getProperty(columnName);
                PlasmaProperty valueProp = prop;
                while (!valueProp.getType().isDataType()) {
                    valueProp = this.statementUtil.getOppositePriKeyProperty(valueProp);
                }
                Object value = converter.fromJDBCDataType(rs, i, columnType, valueProp);
                if (value != null) {
                    PropertyPair pair = new PropertyPair((PlasmaProperty) prop, value);
                    if (!valueProp.equals(prop))
                        pair.setValueProp(valueProp);
                    if (!props.contains(prop))
                        pair.setQueryProperty(false);
                    row.add(pair);
                }
            }
            count++;
        }
        if (log.isDebugEnabled())
            log.debug("returned " + count + " results");
    } catch (Throwable t) {
        throw new DataAccessException(t);
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }
    return result;
}

From source file:com.gdcn.modules.db.jdbc.processor.CamelBeanProcessor.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.//www . ja v a2 s.  c  om
 *
 * @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);
        }
        columnName = columnName.toLowerCase();
        String propertyName = columnToPropertyOverrides.get(columnName);
        if (propertyName == null) {
            propertyName = EncodeUtils.underline2camel(columnName);//?
        }
        for (int i = 0; i < props.length; i++) {
            String prop = props[i].getName();
            if (propertyName.equalsIgnoreCase(prop)) {
                columnToProperty[col] = i;
                break;
            }
        }
    }
    return columnToProperty;
}

From source file:cz.lbenda.dataman.db.DbStructureFactory.java

private void writeColumnNames(String columnsFrom, ResultSetMetaData metaData) throws SQLException {
    if (Constants.IS_IN_DEVELOP_MODE) {
        if (!columnsFromWriten.contains(columnsFrom)) {
            LOG.debug("Write column names: " + columnsFrom);
            columnsFromWriten.add(columnsFrom);
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                LOG.debug("Column: " + metaData.getColumnName(i) + " : " + metaData.getColumnLabel(i));
            }/*from  w  ww  . j a  v a  2  s.c  o m*/
        }
    }
}

From source file:com.xpfriend.fixture.cast.temp.Database.java

private String getColumnLabel(ResultSetMetaData md, int column) throws SQLException {
    try {/*from w w  w  . j  ava 2s .c o m*/
        String label = md.getColumnLabel(column);
        if (!Strings.isEmpty(label)) {
            return label;
        }
    } catch (Exception e) {
        ExceptionHandler.ignore(e);
    }
    return md.getColumnName(column);
}

From source file:com.cloudera.sqoop.manager.SqlManager.java

/**
 * Get column names for a query statement that we do not modify further.
 *//*from  ww w.j  a v a2  s . co  m*/
public String[] getColumnNamesForRawQuery(String stmt) {
    ResultSet results;
    try {
        results = execute(stmt);
    } catch (SQLException sqlE) {
        LOG.error("Error executing statement: " + sqlE.toString(), sqlE);
        release();
        return null;
    }

    try {
        int cols = results.getMetaData().getColumnCount();
        ArrayList<String> columns = new ArrayList<String>();
        ResultSetMetaData metadata = results.getMetaData();
        for (int i = 1; i < cols + 1; i++) {
            String colName = metadata.getColumnName(i);
            if (colName == null || colName.equals("")) {
                colName = metadata.getColumnLabel(i);
                if (null == colName) {
                    colName = "_RESULT_" + i;
                }
            }
            columns.add(colName);
        }
        return columns.toArray(new String[0]);
    } catch (SQLException sqlException) {
        LOG.error("Error reading from database: " + sqlException.toString(), sqlException);
        return null;
    } finally {
        try {
            results.close();
            getConnection().commit();
        } catch (SQLException sqlE) {
            LOG.warn("SQLException closing ResultSet: " + sqlE.toString(), sqlE);
        }

        release();
    }
}

From source file:com.gmail.sretof.db.jdbc.processor.CamelBeanProcessor.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>.
 * // w w  w .j  a  v a  2s .c  om
 * @param rsmd
 *            The <code>ResultSetMetaData</code> containing column
 *            information.
 * 
 * @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);
        }
        columnName = columnName.toLowerCase();
        String propertyName = columnToPropertyOverrides.get(columnName);
        if (propertyName == null) {
            propertyName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName);// ?
        }
        for (int i = 0; i < props.length; i++) {
            String prop = props[i].getName();
            if (propertyName.equalsIgnoreCase(prop)) {
                columnToProperty[col] = i;
                break;
            }
        }
    }
    return columnToProperty;
}

From source file:org.h2gis.drivers.geojson.GeoJsonWriteDriver.java

/**
 * Cache the column name and its index./*from ww w  .jav a  2  s .  co  m*/
 *
 * @param resultSetMetaData
 * @throws SQLException
 */
private void cacheMetadata(ResultSetMetaData resultSetMetaData) throws SQLException {
    cachedColumnNames = new HashMap<String, Integer>();
    for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
        final String fieldTypeName = resultSetMetaData.getColumnTypeName(i);
        if (!fieldTypeName.equalsIgnoreCase("geometry")
                && isSupportedPropertyType(resultSetMetaData.getColumnType(i), fieldTypeName)) {
            cachedColumnNames.put(resultSetMetaData.getColumnName(i).toUpperCase(), i);
            columnCountProperties++;
        }
    }
}