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:ProxyAuthTest.java

private static void runQuery(String sqlStmt) throws Exception {
    Statement stmt = con.createStatement();
    ResultSet res = stmt.executeQuery(sqlStmt);

    ResultSetMetaData meta = res.getMetaData();
    System.out.println("Resultset has " + meta.getColumnCount() + " columns");
    for (int i = 1; i <= meta.getColumnCount(); i++) {
        System.out.println(//from  w  w  w  .j  a v a  2s  .c o  m
                "Column #" + i + " Name: " + meta.getColumnName(i) + " Type: " + meta.getColumnType(i));
    }

    while (res.next()) {
        for (int i = 1; i <= meta.getColumnCount(); i++) {
            System.out.println("Column #" + i + ": " + res.getString(i));
        }
    }
    res.close();
    stmt.close();
}

From source file:AIR.Common.DB.AbstractDLL.java

public static boolean hasColumn(ResultSet reader, String columnName) throws SQLException {
    ResultSetMetaData metaData = reader.getMetaData();
    for (int i = 1; i <= metaData.getColumnCount(); ++i) {
        if ((metaData.getColumnName(i).equals(columnName))) {
            return true;
        }/*from  www. jav  a  2  s.  c o m*/
    }
    return false;
}

From source file:com.tesora.dve.client.ClientTestNG.java

private static void verifyMetadata(ResultSetMetaData rsmd, String[] namesAndAliases) throws SQLException {
    if (namesAndAliases == null) {
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            System.out.println(rsmd.getColumnName(i) + " as " + rsmd.getColumnLabel(i));
        }/*from   w w  w .  jav a 2s  .  co  m*/
        return;
    }
    int ncolumns = namesAndAliases.length / 2;
    assertEquals(ncolumns, rsmd.getColumnCount());
    for (int i = 0; i < ncolumns; i++) {
        String ename = namesAndAliases[2 * i];
        String ealias = namesAndAliases[2 * i + 1];
        assertEquals(ename, rsmd.getColumnName(i + 1));
        assertEquals(ealias, rsmd.getColumnLabel(i + 1));
    }
}

From source file:com.hangum.tadpole.engine.sql.util.resultset.ResultSetUtils.java

/**
 * column name of table//  ww w.j  a  va  2 s  .  c  o m
 * 
 * @param isShowRowNum
 * @param rs
 * @return
 * @throws Exception
 */
public static Map<Integer, String> getColumnName(boolean isShowRowNum, ResultSet rs) throws Exception {
    Map<Integer, String> mapColumnName = new HashMap<Integer, String>();
    int intStartIndex = 0;

    if (isShowRowNum) {
        intStartIndex++;
        mapColumnName.put(0, "#");
    }

    ResultSetMetaData rsm = rs.getMetaData();
    for (int i = 0; i < rsm.getColumnCount(); i++) {
        mapColumnName.put(i + intStartIndex, rsm.getColumnName(i + 1));
    }

    return mapColumnName;
}

From source file:com.splicemachine.homeless.TestUtils.java

private static Map<String, Object> resultSetToOrderedMap(ResultSet rs) throws SQLException {
    Map<String, Object> result = new LinkedHashMap<>();
    ResultSetMetaData rsmd = rs.getMetaData();
    int cols = rsmd.getColumnCount();

    for (int i = 1; i <= cols; i++) {
        result.put(rsmd.getColumnName(i), rs.getObject(i));
    }//from   w w w .j  a va 2s . co  m

    return result;
}

From source file:Main.java

public static String convertResultSetToXML(ResultSet rs)
        throws SQLException, ParserConfigurationException, TransformerException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element results = doc.createElement("Results");
    doc.appendChild(results);/* www  .j a v a 2  s .co m*/

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);
        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);
            if (value != null) {
                Element node = doc.createElement(columnName.replaceAll("\\(", "_").replaceAll("\\)", "_"));
                node.appendChild(doc.createTextNode(value.toString()));
                row.appendChild(node);
            }
        }
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

    return output;
}

From source file:com.viettel.ws.client.JDBCUtil.java

/**
 * Create document using DOM api/* ww w . j a  va 2 s.c  o m*/
 *
 * @param rs a result set
 * @return A document of a result set
 * @throws ParserConfigurationException - If error when parse string
 * @throws SQLException - If error when read data from database
 */
public static Document toDocument(ResultSet rs) throws ParserConfigurationException, SQLException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setFeature(FEATURE_GENERAL_ENTITIES, false);
    factory.setFeature(FEATURE_PARAMETER_ENTITIES, false);
    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();

    Element results = doc.createElement("Results");
    doc.appendChild(results);

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);

        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);

            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);
        }
    }
    return doc;
}

From source file:com.xqdev.sql.MLSQL.java

private static void addResultSet(Element root, ResultSet rs) throws SQLException {
    Namespace sql = root.getNamespace();

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    while (rs.next()) {
        Element tuple = new Element("tuple", sql);
        for (int i = 1; i <= columnCount; i++) {
            String colName = rsmd.getColumnName(i); // names aren't guaranteed OK in xml
            String colTypeName = rsmd.getColumnTypeName(i);

            // Decode a BLOB if one is found and place it into the result as a encoded Base 64 string
            String colValue = "";
            if ("BLOB".equalsIgnoreCase(colTypeName)) {
                Blob b = rs.getBlob(i);
                if (b != null && b.length() > 0) {
                    Base64 b64 = new Base64();
                    String b64Blob = b64.encodeBase64String(b.getBytes(1, (int) b.length()));
                    colValue = b64Blob;
                } else
                    colValue = "";
            } else {
                colValue = rs.getString(i);
            }//from  w  w  w .  j  a v a 2  s. co  m

            boolean wasNull = rs.wasNull();
            Element elt = new Element(colName);
            if (wasNull) {
                elt.setAttribute("null", "true");
            }
            if ("UNKNOWN".equalsIgnoreCase(colTypeName)) {
                tuple.addContent(elt.setText("UNKNOWN TYPE")); // XXX ugly
            } else {
                tuple.addContent(elt.setText(colValue));
            }
        }
        root.addContent(tuple);
    }

}

From source file:com.viettel.ws.client.JDBCUtil.java

/**
 * Create xml string - fastest, but may have encoding issues
 *
 * @param rs - a Result set//ww w. j a  v a 2s . co  m
 * @return - XML string of a result set
 * @throws SQLException - If error when read data from database
 */
public static String toXML(ResultSet rs) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();
    StringBuilder xml = new StringBuilder();
    xml.append("<Results>");

    while (rs.next()) {
        xml.append("<Row>");

        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);
            xml.append("<").append(columnName).append(">");

            if (value != null) {
                xml.append(value.toString().trim());
            }
            xml.append("</").append(columnName).append(">");
        }
        xml.append("</Row>");
    }

    xml.append("</Results>");

    return xml.toString();
}

From source file:es.tena.foundation.util.POIUtil.java

private static void generate(Writer out, ResultSet rset, String encoding) throws Exception {
    SimpleDateFormat sdfecha = new SimpleDateFormat("dd/MM/yyyy");
    SpreadSheetWriter sw = new SpreadSheetWriter(out);
    sw.beginSheet();//from   w  ww . j  ava  2s .  c  o  m
    ResultSetMetaData rmd = rset.getMetaData();

    HashMap<Integer, String> columnas = new HashMap<Integer, String>();
    //creamos la cabecera del excel
    sw.insertRow(0);
    int numeroColumnas = rmd.getColumnCount();
    for (int numeroColumna = 1; numeroColumna <= numeroColumnas; numeroColumna++) {
        String nombreColumna = rmd.getColumnName(numeroColumna).toUpperCase();
        columnas.put(numeroColumna, rmd.getColumnTypeName(numeroColumna));
        sw.createCell(numeroColumna - 1, nombreColumna);
    }

    sw.endRow();

    //creamos los datos del excel
    int rowNum = 1;
    while (rset.next()) {
        sw.insertRow(rowNum);
        for (int columna = 1; columna <= numeroColumnas; columna++) {
            if (columnas.get(columna).equals("CHAR") || columnas.get(columna).equals("VARCHAR2")) {
                String valor = "";
                valor = rset.getString(columna);
                valor = fixPOICellValue(valor, encoding);
                if (valor == null || valor.toLowerCase().equals("null")) {
                    valor = "";
                }
                sw.createCell(columna - 1, valor);
            } else if (columnas.get(columna).equals("DATE")) {
                Date fecha = new Date();
                fecha = rset.getDate(columna);
                String valor = (fecha != null) ? sdfecha.format(fecha) : null;
                if (valor == null || valor.toLowerCase().equals("null")) {
                    valor = "";
                }
                sw.createCell(columna - 1, valor);
            } else if (columnas.get(columna).equals("NUMBER")) {
                String valor = "";
                valor = rset.getString(columna);
                if (valor == null || valor.toLowerCase().equals("null")) {
                    valor = "";
                }
                sw.createCell(columna - 1, valor);
            } else {
                String valor = "";
                valor = rset.getString(columna);
                valor = fixPOICellValue(valor, encoding);
                if (valor == null || valor.toLowerCase().equals("null")) {
                    valor = "";
                }
                sw.createCell(columna - 1, valor);
            }
        }
        sw.endRow();
        rowNum++;
    }
    sw.endSheet();
}