Example usage for java.sql ResultSetMetaData getColumnCount

List of usage examples for java.sql ResultSetMetaData getColumnCount

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnCount.

Prototype

int getColumnCount() throws SQLException;

Source Link

Document

Returns the number of columns in this ResultSet object.

Usage

From source file:com.nextep.designer.sqlclient.ui.helpers.SQLHelper.java

public static INextepMetadata createOfflineMetadata(ResultSetMetaData md, String sqlQuery) throws SQLException {
    final NextepResultSetMetaData nmd = new NextepResultSetMetaData();
    DMLParseResult parseResult = null;//from  www  .j  a va  2 s  . c o  m
    nmd.setColumnCount(md.getColumnCount());
    for (int i = 1; i <= md.getColumnCount(); i++) {
        nmd.setColumnName(i, md.getColumnName(i));
        nmd.setColumnType(i, md.getColumnType(i));
        // Fetching tablename from driver
        String tableName = md.getTableName(i);
        // If not available we try to parse ourselves
        if (tableName == null || "".equals(tableName)) {
            // Parsing
            if (parseResult == null) {
                try {
                    parseResult = parseSQL(sqlQuery, 1);
                } catch (RuntimeException e) {
                    LOGGER.error("Error while parsing SQL : " + e.getMessage(), e);
                }
            }
            // Only providing name on single table select
            if (parseResult != null && parseResult.getFromTables().size() == 1) {
                tableName = parseResult.getFromTables().iterator().next().getTableName();
            }
        }
        nmd.setTableName(i, tableName);
    }
    return nmd;
}

From source file:com.zimbra.cs.mailbox.util.MetadataDump.java

private static List<Row> getRevisionRows(DbConnection conn, int groupId, int mboxId, int itemId,
        boolean fromDumpster) throws ServiceException {
    PreparedStatement stmt = null;
    ResultSet rs = null;/*from  www.j av a2  s .  co m*/
    try {
        String sql = "SELECT * FROM " + DbMailItem.getRevisionTableName(groupId, fromDumpster)
                + " WHERE mailbox_id = " + mboxId + " AND item_id = " + itemId
                + " ORDER BY mailbox_id, item_id, version DESC";
        stmt = conn.prepareStatement(sql);
        rs = stmt.executeQuery();
        List<Row> rows = new ArrayList<Row>();
        while (rs.next()) {
            Row row = new Row();
            ResultSetMetaData rsMeta = rs.getMetaData();
            int cols = rsMeta.getColumnCount();
            for (int i = 1; i <= cols; i++) {
                String colName = rsMeta.getColumnName(i);
                String colValue = rs.getString(i);
                if (rs.wasNull())
                    colValue = null;
                row.addColumn(colName, colValue);
            }
            rows.add(row);
        }
        return rows;
    } catch (SQLException e) {
        throw ServiceException.INVALID_REQUEST("No such item: mbox=" + mboxId + ", item=" + itemId, e);
    } finally {
        DbPool.closeResults(rs);
        DbPool.closeStatement(stmt);
    }
}

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

/**
 * Create document using DOM api/*from w w w .ja  v a2  s .  c  om*/
 *
 * @param rs a result set
 * @param doc a input document for append content
 * @param rsName name of the appended element
 * @return a document after append content
 * @throws ParserConfigurationException If error when parse XML string
 * @throws SQLException If error when read data from database
 */
public static Document add2Document1(ResultSet rs1, ResultSet rs2, Document doc, String rsName)
        throws ParserConfigurationException, SQLException {

    if (rs1 == null && rs2 == null) {
        return doc;
    }

    //Get root element
    Element root = doc.getDocumentElement();

    Element rsElement = doc.createElement(rsName);
    root.appendChild(rsElement);

    if (rs1 != null) {
        ResultSetMetaData rsmd = rs1.getMetaData();
        int colCount = rsmd.getColumnCount();

        while (rs1.next()) {
            Element row = doc.createElement("Row");
            rsElement.appendChild(row);
            try {
                for (int i = 1; i <= colCount; i++) {
                    String columnName = rsmd.getColumnName(i);
                    Object value = rs1.getObject(i);
                    if (value == null) {
                        value = "";
                    }

                    Element node = doc.createElement(columnName);
                    node.appendChild(doc.createTextNode(value.toString()));
                    row.appendChild(node);
                }
            } catch (Exception ex) {
                LogUtil.addLog(ex);//binhnt sonar a160901
                //                    logger.error(e, e);
            }
        }
    }

    if (rs2 != null) {
        ResultSetMetaData rsmd = rs2.getMetaData();
        int colCount = rsmd.getColumnCount();

        while (rs2.next()) {
            Element row = doc.createElement("Row");
            rsElement.appendChild(row);
            try {
                for (int i = 1; i <= colCount; i++) {
                    String columnName = rsmd.getColumnName(i);
                    Object value = rs2.getObject(i);
                    if (value == null) {
                        value = "";
                    }

                    Element node = doc.createElement(columnName);
                    node.appendChild(doc.createTextNode(value.toString()));
                    row.appendChild(node);
                }
            } catch (Exception ex) {
                LogUtil.addLog(ex);//binhnt sonar a160901
                //                    logger.error(e, e);
            }
        }
    }
    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);
            }//  www .  j a v  a  2s  .c  o  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.streamsets.pipeline.stage.BaseHiveIT.java

/**
 * Validate structure of the result set (column names and types).
 *///from w w  w.j  a va  2  s  .c o m
public static void assertResultSetStructure(ResultSet rs, Pair<String, Integer>... columns) throws Exception {
    ResultSetMetaData metaData = rs.getMetaData();
    Assert.assertEquals(Utils.format("Unexpected number of columns"), columns.length,
            metaData.getColumnCount());
    int i = 1;
    for (Pair<String, Integer> column : columns) {
        Assert.assertEquals(Utils.format("Unexpected name for column {}", i), column.getLeft(),
                metaData.getColumnName(i));
        Assert.assertEquals(Utils.format("Unexpected type for column {}", i), (int) column.getRight(),
                metaData.getColumnType(i));
        i++;
    }
}

From source file:at.alladin.rmbt.statisticServer.StatisticsResource.java

private static void fillJSON(final String lang, final ResultSet rs, final JSONArray providers)
        throws SQLException, JSONException {
    final ResultSetMetaData metaData = rs.getMetaData();
    final int columnCount = metaData.getColumnCount();
    while (rs.next()) {
        final JSONObject obj = new JSONObject();
        for (int j = 1; j <= columnCount; j++) {
            final String colName = metaData.getColumnName(j);
            Object data = rs.getObject(j);
            if (colName.equals("name") && data == null)
                if (lang != null && lang.equals("de"))
                    data = "Andere Betreiber";
                else
                    data = "Other operators";
            if (colName.equals("shortname") && data == null) {
                if (lang != null && lang.equals("de"))
                    data = "Andere";
                else
                    data = "Others";
            }/*from  w  w  w.  j  av  a  2  s. c o  m*/
            obj.put(colName, data);
        }
        providers.put(obj);
    }
}

From source file:ExecSQL.java

/**
     * Prints a result set./*from  w  w  w.jav  a  2  s . c om*/
     * @param stat the statement whose result set should be printed
     */
    public static void showResultSet(Statement stat) throws SQLException {
        ResultSet result = stat.getResultSet();
        ResultSetMetaData metaData = result.getMetaData();
        int columnCount = metaData.getColumnCount();

        for (int i = 1; i <= columnCount; i++) {
            if (i > 1)
                System.out.print(", ");
            System.out.print(metaData.getColumnLabel(i));
        }
        System.out.println();

        while (result.next()) {
            for (int i = 1; i <= columnCount; i++) {
                if (i > 1)
                    System.out.print(", ");
                System.out.print(result.getString(i));
            }
            System.out.println();
        }
        result.close();
    }

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  w  w .  j av a 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();
}

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

/**
 * column name of table//from   w  w  w .ja  v  a2 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.hangum.tadpole.engine.sql.util.resultset.ResultSetUtils.java

/**
 * column label name of table/*from w  ww  .j  av a  2  s  .  co  m*/
 * 
 * @param isShowRowNum
 * @param rs
 * @return
 * @throws Exception
 */
public static Map<Integer, String> getColumnLabelName(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.getColumnLabel(i + 1));
    }

    return mapColumnName;
}