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:io.cloudslang.content.database.utils.Format.java

/**
 * Returns tabular form of resultSet similar to what you would get from
 * running a query from the command line
 *
 * @param result populated result set/*from   ww w.j av  a  2s.c o m*/
 * @param cal    calendar to use to format
 * @return
 * @throws SQLException
 */
private static String resultSetToTable(ResultSet result, Calendar cal, boolean checkNullTermination)
        throws SQLException {
    assert (result != null);

    ResultSetMetaData md = result.getMetaData();
    int nCols = md.getColumnCount();
    String[] headers = new String[nCols];
    int[] headerSz = new int[nCols]; // Note: Eclipse has a friendly getDisplaySizes() function
    int maxWidth = 1; // maximum column width - initially set at 1 to prevent an edge case

    List<String[]> rows = new ArrayList<>(); // columns
    // This is fairly space intensive because we don't want to turn this into an O^2(n) problem
    // instead of a O(n) problem. It's O(n) space but with a k of 2, and same with space.
    // Ugh, stupid time-memory tradeoffs
    // We're storing it ALL in Java data structures to figure out width of columns first, then padding later
    // for serialization
    for (int colheader = 0; colheader < nCols; colheader++) {
        headers[colheader] = md.getColumnLabel(colheader + 1);
        headerSz[colheader] = headers[colheader].length();
    }

    // setup columns to be width of column labels
    while (result.next()) {
        String[] row = new String[headers.length];
        for (int colN = 0; colN < nCols; colN++) {
            String colVal = getColumn(result, colN + 1, checkNullTermination);
            headerSz[colN] = colVal.length() > headerSz[colN] ? colVal.length() : headerSz[colN];
            row[colN] = colVal;
        }
        rows.add(row);
    }
    // column widths set, now start populating the string builder
    StringBuilder resultSb = new StringBuilder(headers.length * maxWidth / 2);
    // construct the headers
    for (int colheader = 0; colheader < nCols; colheader++) {
        resultSb.append(headers[colheader]);
        for (int count = 0; count < headerSz[colheader] - headers[colheader].length() + colPadding; count++)
            resultSb.append(" ");
    }
    resultSb.append(NEW_LINE);
    for (int colheader = 0; colheader < nCols; colheader++) {
        for (int count = 0; count < headerSz[colheader]; count++)
            resultSb.append("-");
        for (int count = 0; count < colPadding; count++)
            resultSb.append(" ");
    }
    resultSb.append(NEW_LINE);
    // now append the data itself
    for (String[] row : rows) {
        for (int col = 0; col < nCols; col++) {
            resultSb.append(row[col]);
            for (int padIdx = 0; padIdx < headerSz[col] - row[col].length() + colPadding; padIdx++)
                resultSb.append(" ");
        }
        resultSb.append(NEW_LINE);
    }

    return resultSb.toString();
}

From source file:eagle.storage.jdbc.entity.JdbcEntitySerDeserHelper.java

/**
 *
 * @param resultSet//from w  ww  .  j av  a2  s  .  co m
 * @param entityDefinition
 * @return
 * @throws SQLException
 * @throws IOException
 */
public static Map<String, Object> readInternal(ResultSet resultSet, JdbcEntityDefinition entityDefinition)
        throws SQLException, IOException {
    ResultSetMetaData metadata = resultSet.getMetaData();
    int columnCount = metadata.getColumnCount();
    Map<String, Object> row = new HashMap<String, Object>();
    for (int i = 1; i <= columnCount; i++) {
        String columnName = metadata.getColumnName(i);
        JdbcSerDeser serDeser = entityDefinition.getJdbcSerDeser(columnName);
        if (serDeser == null) {
            throw new IOException("SQLSerDeser for column: " + columnName + " is null");
        }
        Object value = serDeser.readValue(resultSet, columnName, entityDefinition);
        row.put(columnName, value);
    }
    return row;
}

From source file:Student.java

public static void checkData() throws Exception {
        Class.forName("org.hsqldb.jdbcDriver");
        Connection conn = DriverManager.getConnection("jdbc:hsqldb:data/tutorial", "sa", "");
        Statement st = conn.createStatement();

        ResultSet mrs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
        while (mrs.next()) {
            String tableName = mrs.getString(3);
            System.out.println("\n\n\n\nTable Name: " + tableName);

            ResultSet rs = st.executeQuery("select * from " + tableName);
            ResultSetMetaData metadata = rs.getMetaData();
            while (rs.next()) {
                System.out.println(" Row:");
                for (int i = 0; i < metadata.getColumnCount(); i++) {
                    System.out.println("    Column Name: " + metadata.getColumnLabel(i + 1) + ",  ");
                    System.out.println("    Column Type: " + metadata.getColumnTypeName(i + 1) + ":  ");
                    Object value = rs.getObject(i + 1);
                    System.out.println("    Column Value: " + value + "\n");
                }//from  w  w  w.ja va2s.  c o  m
            }
        }
    }

From source file:common.DB.java

public static ResultList query(String query) {
    ArrayList list = new ArrayList();
    ResultList result = new ResultList(list);
    try {/*  w  w w .ja  v a2s  .  com*/
        DB.getConnection();

        if (connection != null) {
            statement = connection.createStatement();
            resultSet = statement.executeQuery(query);
            ResultSetMetaData md = resultSet.getMetaData();
            int columns = md.getColumnCount();
            list.add(new HashMap(columns));
            while (resultSet.next()) {
                HashMap row = new HashMap(columns);
                for (int i = 1; i <= columns; ++i) {
                    row.put(md.getColumnLabel(i), resultSet.getString(i));
                }
                list.add(row);
            }
        } else {
            return null;
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    close();
    return result;
}

From source file:mangotiger.sql.SQL.java

public static Map<String, List<Object>> map(final Connection connection, final String sql,
        final Object[] parameters) throws SQLException {
    ResultSet resultSet = null;/*from   w  ww  .jav a 2 s  .co  m*/
    PreparedStatement statement = null;
    try {
        final Map<String, List<Object>> map = new TreeMap<String, List<Object>>();
        statement = newPreparedStatement(connection, sql, parameters);
        resultSet = statement.executeQuery();
        final ResultSetMetaData metaData = resultSet.getMetaData();
        final int columnCount = metaData.getColumnCount();
        for (int i = 0; i < columnCount; ++i) {
            final String columnName = metaData.getColumnName(i);
            map.put(columnName, new ArrayList<Object>());
        }
        while (resultSet.next()) {
            for (int i = 0; i < columnCount; ++i) {
                final String columnName = metaData.getColumnName(i);
                map.get(columnName).add(resultSet.getObject(1));
            }
        }
        return map;
    } catch (SQLException e) {
        log().error("unable to execute: " + asString(sql, parameters), e);
        throw e;
    } finally {
        close(statement, resultSet);
    }
}

From source file:com.adaptris.core.util.JdbcUtil.java

public static Connection testConnection(Connection sqlConnection, String testStatement, boolean debugMode)
        throws SQLException {
    Statement stmt = sqlConnection.createStatement();
    ResultSet rs = null;/*  w  ww  .  j a  v  a 2s .  c o m*/
    try {
        if (isEmpty(testStatement)) {
            return sqlConnection;
        }
        if (debugMode) {
            rs = stmt.executeQuery(testStatement);
            if (rs.next()) {
                StringBuffer sb = new StringBuffer("TestStatement Results - ");
                ResultSetMetaData rsm = rs.getMetaData();
                for (int i = 1; i <= rsm.getColumnCount(); i++) {
                    sb.append("[");
                    sb.append(rsm.getColumnName(i));
                    sb.append("=");
                    sb.append(rs.getObject(i));
                    sb.append("] ");
                }
                log.trace(sb.toString());
            }
        } else {
            stmt.execute(testStatement);
        }
    } finally {
        JdbcUtil.closeQuietly(rs);
        JdbcUtil.closeQuietly(stmt);
    }
    return sqlConnection;
}

From source file:mangotiger.sql.SQL.java

public static List<Object> list(final Connection connection, final String sql, final Object[] parameters)
        throws SQLException {
    ResultSet resultSet = null;/*w  ww .j  a v  a2s  .c o  m*/
    PreparedStatement statement = null;
    try {
        final List<Object> list = new ArrayList<Object>();
        statement = newPreparedStatement(connection, sql, parameters);
        resultSet = statement.executeQuery();
        final ResultSetMetaData metaData = resultSet.getMetaData();
        final int columnCount = metaData.getColumnCount();
        while (resultSet.next()) {
            switch (columnCount) {
            case 1:
                list.add(resultSet.getObject(1));
                break;
            default:
                final Object[] row = new Object[columnCount];
                for (int i = 0; i < columnCount; ++i) {
                    row[i] = resultSet.getObject(i + 1);
                }
                list.add(row);
                break;
            }
        }
        return list;
    } catch (SQLException e) {
        log().error("unable to execute: " + asString(sql, parameters), e);
        throw e;
    } finally {
        close(statement, resultSet);
    }
}

From source file:it.alidays.mapengine.codegenerator.MapperEngineCodeGenerator.java

private static void manageRetrieve(Retrieve retrieve, Connection connection, String packageName,
        File destinationDir)/*w  w  w.ja va  2 s .co m*/
        throws SQLException, JClassAlreadyExistsException, IOException, MapperEngineCodeGeneratorException {
    logger.info("Generating map for {}", retrieve.getId());

    int vuidCount = RetrieveHandler.getVuidCount(retrieve.getContent());
    String content = retrieve.getContent().replaceAll(RetrieveHandler.VUID_KEY, "?");

    Map<String, Integer> columns = new LinkedHashMap<>();

    logger.info("\tRetrieving columns' name");
    try (PreparedStatement preparedStatement = connection.prepareStatement(content)) {
        for (int index = 1; index <= vuidCount; index++) {
            preparedStatement.setObject(index, "_");
        }

        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        for (int i = 1, n = resultSetMetaData.getColumnCount(); i <= n; i++) {
            String columnName = Utils.arrangeColumnName(resultSetMetaData.getColumnLabel(i));
            Integer columnType = resultSetMetaData.getColumnType(i);
            columns.put(columnName, columnType);
        }
    }
    logger.info("\tRetrieved {} columns' name", columns.size());

    createMapClass(retrieve, columns, packageName, destinationDir);
    createRetrieveClass(retrieve, packageName, destinationDir);

    logger.info("Map successfully generated for {}", retrieve.getId());
}

From source file:ca.sqlpower.persistance.CatNap.java

public static void load(Connection con, String tableName, Object loadTo, String where)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLException {
    BeanUtils.describe(loadTo);//from   w w w . j a v  a  2s  .  c  o m
    Statement stmt = null;
    StringBuffer sql = new StringBuffer();
    try {
        sql.append("SELECT * FROM " + tableName + " WHERE " + where);
        sql.append("\n");

        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql.toString());
        while (rs.next()) {
            ResultSetMetaData metaData = rs.getMetaData();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                String beanPropertyName = underscoreToCamelCaps(metaData.getColumnName(i).toLowerCase());

                BeanUtils.setProperty(loadTo, beanPropertyName, rs.getObject(i));

            }
        }
    } catch (SQLException ex) {
        System.err.println("Catnap: Insert failed. Statement was:\n" + sql);
        throw ex;
    } finally {
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException ex) {
            System.err.println(
                    "Catnap: Couldn't close the statement.  Damn.  But at least you won a stack trace:");
            ex.printStackTrace();
        }
    }
}

From source file:io.cloudslang.content.database.services.SQLCommandService.java

public static String executeSqlCommand(final SQLInputs sqlInputs) throws Exception {
    final ConnectionService connectionService = new ConnectionService();
    try (final Connection connection = connectionService.setUpConnection(sqlInputs)) {

        connection.setReadOnly(false);/*  w  w  w .  j  a v a2 s  . c  o  m*/

        final String dbType = sqlInputs.getDbType();
        if (ORACLE_DB_TYPE.equalsIgnoreCase(dbType)
                && sqlInputs.getSqlCommand().toLowerCase().contains(DBMS_OUTPUT)) {

            final PreparedStatement preparedStatement = connection.prepareStatement(sqlInputs.getSqlCommand());
            preparedStatement.setQueryTimeout(sqlInputs.getTimeout());
            OracleDbmsOutput oracleDbmsOutput = new OracleDbmsOutput(connection);
            preparedStatement.executeQuery();
            sqlInputs.setIUpdateCount(preparedStatement.getUpdateCount());
            preparedStatement.close();
            final String output = oracleDbmsOutput.getOutput();
            oracleDbmsOutput.close();
            return output;
        } else {
            final Statement statement = connection.createStatement(sqlInputs.getResultSetType(),
                    sqlInputs.getResultSetConcurrency());
            statement.setQueryTimeout(sqlInputs.getTimeout());
            try {
                statement.execute(sqlInputs.getSqlCommand());
            } catch (SQLException e) {
                if (SYBASE_DB_TYPE.equalsIgnoreCase(dbType)) {
                    //during a dump sybase sends back status as exceptions.
                    if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dump")) {
                        return SQLUtils.processDumpException(e);
                    } else if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("load")) {
                        return SQLUtils.processLoadException(e);
                    }
                } else {
                    throw e;
                }
            }

            ResultSet rs = statement.getResultSet();
            if (rs != null) {
                ResultSetMetaData rsMtd = rs.getMetaData();
                if (rsMtd != null) {
                    sqlInputs.getLRows().clear();
                    int colCount = rsMtd.getColumnCount();

                    if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dbcc")) {
                        while (rs.next()) {
                            if (colCount >= 4) {
                                sqlInputs.getLRows().add(rs.getString(4));
                            }
                        }
                    } else {
                        String delimiter = (StringUtils.isNoneEmpty(sqlInputs.getStrDelim()))
                                ? sqlInputs.getStrDelim()
                                : ",";
                        String strRowHolder;
                        while (rs.next()) {
                            strRowHolder = "";
                            for (int i = 1; i <= colCount; i++) {
                                if (i > 1) {
                                    strRowHolder += delimiter;
                                }
                                strRowHolder += rs.getString(i);
                            }
                            sqlInputs.getLRows().add(strRowHolder);
                        }
                    }
                    rs.close();
                }

            }
            //For sybase, when dbcc command is executed, the result is shown in warning message
            else if (dbType.equalsIgnoreCase(SYBASE_DB_TYPE)
                    && sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dbcc")) {
                SQLWarning warning = statement.getWarnings();
                while (warning != null) {
                    sqlInputs.getLRows().add(warning.getMessage());
                    warning = warning.getNextWarning();
                }
            }

            sqlInputs.setIUpdateCount(statement.getUpdateCount());
        }
    }
    return "Command completed successfully";
}