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

@Path("/GetID/{com}")
@JSONP(queryParam = "callback")
@GET/*from  w  w w  . j a v a2  s. com*/
@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:cosmos.sql.TestSql.java

public void testDistinct() throws SQLException {
    loadDriverClass();//from ww  w  .  j  a va 2s  .  c o m
    Connection connection = null;
    Statement statement = null;
    try {
        Properties info = new Properties();
        info.put("url", JDBC_URL);
        info.put("user", USER);
        info.put("password", PASSWORD);
        connection = DriverManager.getConnection("jdbc:accumulo:cosmos//localhost", info);
        statement = connection.createStatement();
        final ResultSet resultSet = statement.executeQuery("select DISTINCT \"PAGE_ID\" from \""
                + CosmosDriver.COSMOS + "\".\"" + meataData.uuid() + "\"");
        final ResultSetMetaData metaData = resultSet.getMetaData();
        final int columnCount = metaData.getColumnCount();

        assertEquals(columnCount, 1);

        int resultsFound = 0;
        while (resultSet.next()) {
            assertEquals(metaData.getColumnName(1), "PAGE_ID");
            Object value = resultSet.getObject("PAGE_ID");

        }

        assertEquals(resultsFound, 2);
    } finally {
        close(connection, statement);
    }
}

From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.StandardRowSetBuilder.java

private FieldFormatter[] buildFormatterArray(ResultSetMetaData rsm,
        Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter)
        throws Exception {
    FieldFormatter[] fFA = new FieldFormatter[rsm.getColumnCount() + 1];

    for (int i = 1; i < fFA.length; i++) {
        FieldFormatter fF = fieldNameToFormatter.get(rsm.getColumnName(i));
        if (fF == null) {
            fF = fieldIdToFormatter.get("" + i);
        }/*from w ww.j a  v  a2s  .  c o  m*/
        fFA[i] = fF;
    }
    return fFA;
}

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

private String resultToDisplay(ResultSet result, int issue, String note) throws Exception {
    StringBuilder sb = new StringBuilder("Test Issue #" + issue + " - " + note + "\n");
    ResultSetMetaData metadata = result.getMetaData();

    int colCount = metadata.getColumnCount();

    sb.append("--------------").append("\n");
    while (result.next()) {
        metadata = result.getMetaData();
        colCount = metadata.getColumnCount();
        sb.append(String.format("(%d) ", result.getRow()));
        for (int i = 1; i <= colCount; i++) {
            sb.append(showColumn(i, result) + " ");
        }/*from  w ww.j a va2s .  co  m*/
        sb.append("\n");
    }

    return sb.toString();
}

From source file:com.erbjuder.logger.server.rest.util.ResultSetConverter.java

private List<LogMessage> toLogMessageInternal(ResultSet rs, List<LogMessage> logMessages) {

    try {/*from   w ww  . j  a va2s  .co m*/

        // we will need the column names.
        java.sql.ResultSetMetaData rsmd = rs.getMetaData();
        //loop through the ResultSet
        while (rs.next()) {

            //figure out how many columns there are
            int numColumns = rsmd.getColumnCount();

            //each row in the ResultSet will be converted to a Object
            LogMessage obj = new LogMessage();

            // loop through all the columns 
            for (int i = 1; i < numColumns + 1; i++) {
                String column_name = rsmd.getColumnName(i);

                if (column_name.equals("ID")) {
                    obj.setId(rs.getBigDecimal(column_name).longValueExact());
                }

                if (column_name.equals("APPLICATIONNAME")) {
                    obj.setApplicationName(rs.getNString(column_name));
                }

                if (column_name.equals("EXPIREDDATE")) {
                    obj.setExpiredDate(rs.getDate(column_name));
                }

                if (column_name.equals("FLOWNAME")) {
                    obj.setFlowName(rs.getNString(column_name));
                }

                if (column_name.equals("FLOWPOINTNAME")) {
                    obj.setFlowPointName(rs.getNString(column_name));
                }

                if (column_name.equals("ISERROR")) {
                    obj.setIsError(rs.getBoolean(column_name));
                }

                if (column_name.equals("TRANSACTIONREFERENCEID")) {
                    obj.setTransactionReferenceID(rs.getNString(column_name));
                }

                if (column_name.equals("UTCLOCALTIMESTAMP")) {
                    obj.setUtcLocalTimeStamp(rs.getTimestamp(column_name));
                }

                if (column_name.equals("UTCSERVERTIMESTAMP")) {
                    obj.setUtcServerTimeStamp(rs.getTimestamp(column_name));
                }
            } //end foreach
            logMessages.add(obj);
        } //end while
    } catch (Exception e) {
        e.printStackTrace();
    }

    return logMessages;
}

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  va 2s .c  om*/
    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:com.baifendian.swordfish.execserver.engine.hive.HiveSqlExec.java

/**
 *  sql ? ?, ?,  execute, ?/*from   www  .  j a  v a 2s.c o  m*/
 *
 * @param createFuncs ?
 * @param sqls  sql
 * @param isContinue ?, ???
 * @param resultCallback , ?
 * @param queryLimit ?
 * @param remainTime ?, 
 */
public boolean execute(List<String> createFuncs, List<String> sqls, boolean isContinue,
        ResultCallback resultCallback, Integer queryLimit, int remainTime) {

    // ?
    if (remainTime <= 0) {
        return false;
    }

    // ?
    queryLimit = (queryLimit != null) ? queryLimit : defaultQueryLimit;

    HiveConnection hiveConnection = null;
    Statement sta = null;
    Thread logThread = null;

    //  hive ?
    HiveService2ConnectionInfo hiveService2ConnectionInfo = hiveUtil.getHiveService2ConnectionInfo(userName);

    logger.info("execution connection information:{}", hiveService2ConnectionInfo);

    HiveService2Client hiveService2Client = hiveUtil.getHiveService2Client();

    try {
        try {
            hiveConnection = hiveService2Client.borrowClient(hiveService2ConnectionInfo);

            sta = hiveConnection.createStatement();
            //        sta.setQueryTimeout(remainTime);

            // 
            logThread = new Thread(new JdbcLogRunnable(sta));
            logThread.setDaemon(true);
            logThread.start();

            // set queue
            if (queueSQL != null) {
                logger.info("hive queue : {}", queueSQL);
                sta.execute(queueSQL);
            }

            //  function
            if (createFuncs != null) {
                for (String createFunc : createFuncs) {
                    logger.info("hive create function sql: {}", createFunc);
                    sta.execute(createFunc);
                }
            }
        } catch (Exception e) {
            logger.error("execute query exception", e);

            // , , ?
            handlerResults(0, sqls, FlowStatus.FAILED, resultCallback);

            return false;
        }

        //  sql ?
        for (int index = 0; index < sqls.size(); ++index) {
            String sql = sqls.get(index);

            Date startTime = new Date();

            logger.info("hive execute sql: {}", sql);

            ExecResult execResult = new ExecResult();
            execResult.setIndex(index);
            execResult.setStm(sql);

            try {
                // ? query  show ?
                if (HiveUtil.isTokQuery(sql) || HiveUtil.isLikeShowStm(sql)) {
                    sta.setMaxRows(queryLimit);
                    ResultSet res = sta.executeQuery(sql);

                    ResultSetMetaData resultSetMetaData = res.getMetaData();
                    int count = resultSetMetaData.getColumnCount();

                    List<String> colums = new ArrayList<>();
                    for (int i = 1; i <= count; i++) {
                        colums.add(resultSetMetaData.getColumnLabel(
                                i)/*parseColumnName(resultSetMetaData.getColumnLabel(i), colums)*/);
                    }

                    execResult.setTitles(colums);

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

                    //  1,  query ?
                    if (count > 1 || HiveUtil.isTokQuery(sql)) {
                        while (res.next()) {
                            List<String> values = new ArrayList<>();
                            for (int i = 1; i <= count; ++i) {
                                values.add(res.getString(i));
                            }

                            datas.add(values);
                        }
                    } else {
                        StringBuffer buffer = new StringBuffer();

                        while (res.next()) {
                            buffer.append(res.getString(1));
                            buffer.append("\n");
                        }

                        List<String> values = new ArrayList<>();
                        values.add(buffer.toString().trim());

                        datas.add(values);
                    }

                    execResult.setValues(datas);
                } else {
                    sta.execute(sql);
                }

                // ??
                execResult.setStatus(FlowStatus.SUCCESS);

                // ?
                if (resultCallback != null) {
                    Date endTime = new Date();
                    resultCallback.handleResult(execResult, startTime, endTime);
                }
            } catch (SQLTimeoutException e) {
                // sql 
                logger.error("executeQuery timeout exception", e);

                handlerResults(index, sqls, FlowStatus.FAILED, resultCallback);
                return false;
            } catch (DaoSemanticException | HiveSQLException e) {
                // 
                logger.error("executeQuery exception", e);

                if (isContinue) {
                    handlerResult(index, sql, FlowStatus.FAILED, resultCallback);
                } else {
                    handlerResults(index, sqls, FlowStatus.FAILED, resultCallback);
                    return false;
                }
            } catch (Exception e) {
                // TTransport 
                if (e.toString().contains("TTransportException")) {
                    logger.error("Get TTransportException return a client", e);
                    // ???
                    //            hiveService2Client.invalidateObject(hiveService2ConnectionInfo, hiveConnection);
                    handlerResults(index, sqls, FlowStatus.FAILED, resultCallback);
                    return false;
                }

                // socket 
                if (e.toString().contains("SocketException")) {
                    logger.error("SocketException clear pool", e);
                    hiveService2Client.clear();
                    handlerResults(index, sqls, FlowStatus.FAILED, resultCallback);
                    return false;
                }

                logger.error("executeQuery exception", e);

                if (isContinue) {
                    handlerResult(index, sql, FlowStatus.FAILED, resultCallback);
                } else {
                    handlerResults(index, sqls, FlowStatus.FAILED, resultCallback);
                    return false;
                }
            }
        }
    } finally {
        // 
        try {
            if (sta != null) {
                sta.close();
            }
        } catch (Exception e) {
            logger.error("Catch an exception", e);
        }

        try {
            // 
            if (hiveConnection != null) {
                // 
                hiveConnection.close();

                // , ??
                hiveService2Client.returnClient(hiveService2ConnectionInfo, hiveConnection);
            }
        } catch (Exception e) {
            logger.error("Catch an exception", e);
        }

        // 
        try {
            if (logThread != null) {
                logThread.interrupt();
                logThread.join(HiveUtil.DEFAULT_QUERY_PROGRESS_THREAD_TIMEOUT);
            }
        } catch (Exception e) {
            //        logger.error("Catch an exception", e);
        }
    }

    return true;
}

From source file:cosmos.sql.TestSql.java

@Test
public void testLimit() throws SQLException {
    loadDriverClass();//w w  w  . j a  v  a  2 s. c om
    Connection connection = null;
    Statement statement = null;
    try {
        Properties info = new Properties();
        info.put("url", JDBC_URL);
        info.put("user", USER);
        info.put("password", PASSWORD);
        connection = DriverManager.getConnection("jdbc:accumulo:cosmos//localhost", info);
        statement = connection.createStatement();
        final ResultSet resultSet = statement.executeQuery("select \"PAGE_ID\" from \"" + CosmosDriver.COSMOS
                + "\".\"" + meataData.uuid() + "\"  limit 2 OFFSET 0");
        final ResultSetMetaData metaData = resultSet.getMetaData();
        final int columnCount = metaData.getColumnCount();

        assertEquals(columnCount, 1);

        int resultsFound = 0;
        while (resultSet.next()) {
            assertEquals(metaData.getColumnName(1), "PAGE_ID");
            @SuppressWarnings("unchecked")
            List<Entry<Column, RecordValue<?>>> sValues = (List<Entry<Column, RecordValue<?>>>) resultSet
                    .getObject("PAGE_ID");
            assertEquals(sValues.size(), 1);
            RecordValue<?> onlyValue = sValues.iterator().next().getValue();
            assertEquals(onlyValue.visibility().toString(), "[en]");

            assertEquals(onlyValue.value(), Integer.valueOf(resultsFound).toString());
            resultsFound++;

        }

        assertEquals(resultsFound, 2);
    } finally {
        close(connection, statement);
    }
}

From source file:cosmos.sql.TestSql.java

@Test
public void testJoin() throws SQLException {
    loadDriverClass();/* w w w .  ja  v a  2  s .  c om*/
    Connection connection = null;
    Statement statement = null;
    try {
        Properties info = new Properties();
        info.put("url", JDBC_URL);
        info.put("user", USER);
        info.put("password", PASSWORD);
        connection = DriverManager.getConnection("jdbc:accumulo:cosmos//localhost", info);
        statement = connection.createStatement();
        final ResultSet resultSet = statement.executeQuery("select \"PAGE_ID\" from \"" + CosmosDriver.COSMOS
                + "\".\"" + meataData.uuid() + "\"  limit 2 OFFSET 0");
        final ResultSetMetaData metaData = resultSet.getMetaData();
        final int columnCount = metaData.getColumnCount();

        assertEquals(columnCount, 1);

        int resultsFound = 0;
        while (resultSet.next()) {
            assertEquals(metaData.getColumnName(1), "PAGE_ID");
            @SuppressWarnings("unchecked")
            List<Entry<Column, RecordValue<?>>> sValues = (List<Entry<Column, RecordValue<?>>>) resultSet
                    .getObject("PAGE_ID");
            assertEquals(sValues.size(), 1);
            RecordValue<?> onlyValue = sValues.iterator().next().getValue();
            assertEquals(onlyValue.visibility().toString(), "[en]");

            assertEquals(onlyValue.value(), Integer.valueOf(resultsFound).toString());
            resultsFound++;

        }

        assertEquals(resultsFound, 2);
    } finally {
        close(connection, statement);
    }
}

From source file:cosmos.sql.TestSql.java

@Test
public void testDisjunctionPositive() throws SQLException {
    loadDriverClass();/*from  w  w  w . java 2 s  . co  m*/
    Connection connection = null;
    Statement statement = null;
    try {
        Properties info = new Properties();
        info.put("url", JDBC_URL);
        info.put("user", USER);
        info.put("password", PASSWORD);
        connection = DriverManager.getConnection("jdbc:accumulo:cosmos//localhost", info);
        statement = connection.createStatement();
        final ResultSet resultSet = statement.executeQuery("select \"PAGE_ID\" from \"" + CosmosDriver.COSMOS
                + "\".\"" + meataData.uuid() + "\"  where PAGE_ID='9' or REVISION_ID='8'");
        final ResultSetMetaData metaData = resultSet.getMetaData();
        final int columnCount = metaData.getColumnCount();

        assertEquals(columnCount, 1);

        int resultsFound = 0;
        while (resultSet.next()) {
            assertEquals(metaData.getColumnName(1), "PAGE_ID");
            @SuppressWarnings("unchecked")
            List<Entry<Column, RecordValue<?>>> sValues = (List<Entry<Column, RecordValue<?>>>) resultSet
                    .getObject("PAGE_ID");
            assertEquals(sValues.size(), 1);
            RecordValue onlyValue = sValues.iterator().next().getValue();
            assertEquals(onlyValue.visibility().toString(), "[en]");

            assertTrue(onlyValue.value().equals(Integer.valueOf(9).toString())
                    || onlyValue.value().equals(Integer.valueOf(8).toString()));
            resultsFound++;

        }

        assertEquals(resultsFound, 2);
    } finally {
        close(connection, statement);
    }
}