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.serphacker.serposcope.db.base.ExportDB.java

public boolean export(Writer writer) throws IOException {
    for (String resource : MigrationDB.DB_SCHEMA_FILES) {
        String sql = new String(ByteStreams.toByteArray(MigrationDB.class.getResourceAsStream(resource)));
        sql = sql.replaceAll("--.*\n", "\n");
        sql = sql.replaceAll("\\s+", " ");
        sql = sql.replaceAll(";\\s*", ";\n");
        writer.append(sql);//from  w w w . ja v a  2s  . co m
        writer.append("\n");
    }

    writer.append("\nSET FOREIGN_KEY_CHECKS=0;\n");
    try (Connection con = ds.getConnection()) {
        for (String table : TABLES) {
            writer.flush();
            try (Statement stmt = con.createStatement()) {
                LOG.info("exporting table {}", table);
                long _start = System.currentTimeMillis();

                stmt.setQueryTimeout(3600 * 24);
                ResultSet rs = stmt.executeQuery("SELECT * FROM `" + table + "`");
                ResultSetMetaData metaData = rs.getMetaData();
                int columns = metaData.getColumnCount();

                String insertStatement = "INSERT INTO `" + table + "` VALUES ";

                StringBuilder stmtBuilder = new StringBuilder(insertStatement);
                while (rs.next()) {

                    StringBuilder entryBuilder = new StringBuilder("(");
                    for (int colIndex = 1; colIndex <= columns; colIndex++) {
                        Object object = rs.getObject(colIndex);
                        String colName = metaData.getColumnName(colIndex);
                        String colClassName = metaData.getColumnClassName(colIndex);
                        String escaped = escape(object, colClassName, colName);
                        entryBuilder.append(escaped);
                        if (colIndex < columns) {
                            entryBuilder.append(',');
                        }
                    }
                    entryBuilder.append("),");

                    if (stmtBuilder.length() != insertStatement.length()
                            && stmtBuilder.length() + entryBuilder.length() > DEFAULT_MAX_ALLOWED_PACKET) {
                        stmtBuilder.setCharAt(stmtBuilder.length() - 1, ';');
                        writer.append(stmtBuilder).append('\n');
                        stmtBuilder = new StringBuilder(insertStatement);
                    }

                    stmtBuilder.append(entryBuilder);
                }

                if (stmtBuilder.length() != insertStatement.length()) {
                    stmtBuilder.setCharAt(stmtBuilder.length() - 1, ';');
                    writer.append(stmtBuilder).append('\n');
                }

                LOG.info("exported table {} in {}", table,
                        DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - _start));
            }
        }
        writer.append("SET FOREIGN_KEY_CHECKS=1;\n");
    } catch (Exception ex) {
        LOG.error("SQL error", ex);
        return false;
    }

    return true;
}

From source file:de.tudarmstadt.ukp.csniper.ml.JdbcCustomReader.java

private void query() {
    try {//  w  ww  .  j  av  a2 s.co m
        Statement statement = sqlConnection.createStatement();

        // execute query which sets user variables
        Iterator<String> it = Arrays.asList(StringUtils.split(setterQuery, "\n")).iterator();
        StringBuilder sb = new StringBuilder();
        while (it.hasNext()) {
            String line = it.next();
            if (line.trim().startsWith("#")) {
                continue;
            } else if (line.trim().endsWith(";")) {
                sb.append(line);
                statement.addBatch(sb.toString());
                sb = new StringBuilder();
            } else {
                sb.append(line);
            }
        }
        statement.executeBatch();

        statement.executeQuery(query);
        resultSet = statement.getResultSet();
        resultSet.last();
        resultSetSize = resultSet.getRow();
        resultSet.beforeFirst();
        completed = 0;

        // Store available column names
        columnNames = new HashSet<String>();
        ResultSetMetaData meta = resultSet.getMetaData();
        for (int i = 1; i < meta.getColumnCount() + 1; i++) {
            String columnName = meta.getColumnLabel(i);
            columnNames.add(columnName);
            if (!CAS_COLUMNS.contains(columnName)) {
                getLogger().warn("Unknown column [" + columnName + "].");
            }
        }
    } catch (SQLException e) {
        throw new RuntimeException("There was an unrecoverable error executing the specified SQL statement.",
                e);
    }
}

From source file:com.haulmont.yarg.loaders.impl.SqlDataLoader.java

@Override
public List<Map<String, Object>> loadData(ReportQuery reportQuery, BandData parentBand,
        Map<String, Object> params) {
    List resList;/*from  www  .  j a  v  a2s .  c o m*/
    final List<OutputValue> outputValues = new ArrayList<OutputValue>();

    String query = reportQuery.getScript();
    if (StringUtils.isBlank(query)) {
        return Collections.emptyList();
    }

    try {
        if (Boolean.TRUE.equals(reportQuery.getProcessTemplate())) {
            query = processQueryTemplate(query, parentBand, params);
        }
        final QueryPack pack = prepareQuery(query, parentBand, params);

        ArrayList<Object> resultingParams = new ArrayList<Object>();
        QueryParameter[] queryParameters = pack.getParams();
        for (QueryParameter queryParameter : queryParameters) {
            if (queryParameter.isSingleValue()) {
                resultingParams.add(queryParameter.getValue());
            } else {
                resultingParams.addAll(queryParameter.getMultipleValues());
            }
        }

        resList = runQuery(reportQuery, pack.getQuery(), resultingParams.toArray(),
                new ResultSetHandler<List>() {
                    @Override
                    public List handle(ResultSet rs) throws SQLException {
                        List<Object[]> resList = new ArrayList<Object[]>();

                        while (rs.next()) {
                            ResultSetMetaData metaData = rs.getMetaData();
                            if (outputValues.size() == 0) {
                                for (int columnIndex = 1; columnIndex <= metaData
                                        .getColumnCount(); columnIndex++) {
                                    String columnName = metaData.getColumnLabel(columnIndex);
                                    OutputValue outputValue = new OutputValue(columnName);
                                    setCaseSensitiveSynonym(columnName, outputValue);
                                    outputValues.add(outputValue);
                                }
                            }

                            Object[] values = new Object[metaData.getColumnCount()];
                            for (int columnIndex = 0; columnIndex < metaData.getColumnCount(); columnIndex++) {
                                values[columnIndex] = convertOutputValue(rs.getObject(columnIndex + 1));
                            }
                            resList.add(values);
                        }

                        return resList;
                    }

                    private void setCaseSensitiveSynonym(String columnName, OutputValue outputValue) {
                        Matcher matcher = Pattern.compile("(?i)as\\s*(" + columnName + ")")
                                .matcher(pack.getQuery());
                        if (matcher.find()) {
                            outputValue.setSynonym(matcher.group(1));
                        }
                    }
                });
    } catch (DataLoadingException e) {
        throw e;
    } catch (Throwable e) {
        throw new DataLoadingException(
                String.format("An error occurred while loading data for data set [%s]", reportQuery.getName()),
                e);
    }

    return fillOutputData(resList, outputValues);
}

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

private String getColumnNames(ResultSetMetaData metaData) throws SQLException {
    StringBuilder sb = new StringBuilder();
    int count = metaData.getColumnCount();
    for (int i = 1; i <= count; i++) {
        sb.append(metaData.getColumnName(i));
        if (i < count)
            sb.append(", ");
    }/*ww  w .j  a  v a  2s .co m*/
    return sb.toString();
}

From source file:com.sangupta.fileanalysis.db.DBResultViewer.java

/**
 * View resutls of a {@link ResultSet}./*from w  w  w .  j a v  a 2 s  .c o  m*/
 * 
 * @param resultSet
 * @throws SQLException 
 */
public void viewResult(ResultSet resultSet) throws SQLException {
    if (resultSet == null) {
        // nothing to do
        return;
    }

    // collect the meta
    ResultSetMetaData meta = resultSet.getMetaData();

    final int numColumns = meta.getColumnCount();
    final int[] displaySizes = new int[numColumns + 1];
    final int[] colType = new int[numColumns + 1];

    for (int index = 1; index <= numColumns; index++) {
        colType[index] = meta.getColumnType(index);
        displaySizes[index] = getColumnSize(meta.getTableName(index), meta.getColumnName(index),
                colType[index]);
    }

    // display the header row
    for (int index = 1; index <= numColumns; index++) {
        center(meta.getColumnLabel(index), displaySizes[index]);
    }
    System.out.println("|");
    for (int index = 1; index <= numColumns; index++) {
        System.out.print("+" + StringUtils.repeat('-', displaySizes[index] + 2));
    }
    System.out.println("+");

    // start iterating over the result set
    int rowsDisplayed = 0;
    int numRecords = 0;
    while (resultSet.next()) {
        // read and display the value
        rowsDisplayed++;
        numRecords++;

        for (int index = 1; index <= numColumns; index++) {
            switch (colType[index]) {
            case Types.DECIMAL:
            case Types.DOUBLE:
            case Types.REAL:
                format(resultSet.getDouble(index), displaySizes[index]);
                continue;

            case Types.INTEGER:
            case Types.SMALLINT:
                format(resultSet.getInt(index), displaySizes[index]);
                continue;

            case Types.VARCHAR:
                format(resultSet.getString(index), displaySizes[index], false);
                continue;

            case Types.TIMESTAMP:
                format(resultSet.getTimestamp(index), displaySizes[index]);
                continue;

            case Types.BIGINT:
                format(resultSet.getBigDecimal(index), displaySizes[index]);
                continue;
            }
        }

        // terminator for row and new line
        System.out.println("|");

        // check for rows displayed
        if (rowsDisplayed == 20) {
            // ask the user if more data needs to be displayed
            String cont = ConsoleUtils.readLine("Type \"it\" for more: ", true);
            if (!"it".equalsIgnoreCase(cont)) {
                break;
            }

            // continue;
            rowsDisplayed = 0;
            continue;
        }
    }

    System.out.println("\nTotal number of records found: " + numRecords);
}

From source file:kr.co.bitnine.octopus.engine.CursorHive.java

@Override
public TupleDesc describe() throws PostgresException {
    if (tupDesc != null)
        return tupDesc;

    prepareConnection();/*from  ww w. j  a v a 2  s.c  om*/
    prepareStatement(0);
    try {
        checkCancel();
        ResultSet rs = stmt.executeQuery();
        checkCancel();
        ResultSetMetaData rsmd = rs.getMetaData();
        int colCnt = rsmd.getColumnCount();
        PostgresAttribute[] attrs = new PostgresAttribute[colCnt];
        for (int i = 0; i < colCnt; i++) {
            String colName = getColumnName(rsmd.getColumnName(i + 1));
            int colType = rsmd.getColumnType(i + 1);
            LOG.debug("JDBC type of column '" + colName + "' is " + colType);
            PostgresType type = TypeInfo.postresTypeOfJdbcType(colType);
            int typeInfo = -1;
            if (type == PostgresType.VARCHAR)
                typeInfo = rsmd.getColumnDisplaySize(i + 1);
            attrs[i] = new PostgresAttribute(colName, type, typeInfo);
        }
        rs.close();
        stmt.close();
        stmt = null;

        tupDesc = new TupleDesc(attrs, getResultFormats());
        return tupDesc;
    } catch (SQLException e) {
        PostgresErrorData edata = new PostgresErrorData(PostgresSeverity.ERROR,
                "failed to execute by-pass query: " + e.getMessage());
        throw new PostgresException(edata, e);
    }
}

From source file:com.netspective.sparx.sql.QueryResultSetDataSource.java

protected void setResultSet(ResultSet resultSet) {
    this.resultSet = queryResultSet.getResultSet();

    try {/*w w w. j a v  a  2 s  . c om*/
        if (cacheColumnData) {
            final ResultSetMetaData metaData = resultSet.getMetaData();
            retrievedColumnData = new boolean[metaData.getColumnCount()];
            cachedColumnData = new Object[metaData.getColumnCount()];
        }
        scrollable = resultSet.getType() != ResultSet.TYPE_FORWARD_ONLY ? true : false;
    } catch (SQLException e) {
        log.error("Unable to set result set", e);
        throw new NestableRuntimeException(e);
    }

    activeRowIndex = -1;
    calculatedTotalRows = false;
}

From source file:annis.sqlgen.FrequencySqlGenerator.java

@Override
public FrequencyTable extractData(ResultSet rs) throws SQLException, DataAccessException {
    FrequencyTable result = new FrequencyTable();

    ResultSetMetaData meta = rs.getMetaData();

    while (rs.next()) {
        Validate.isTrue(meta.getColumnCount() > 1, "frequency table extractor needs at least 2 columns");

        Validate.isTrue("count".equalsIgnoreCase(meta.getColumnName(meta.getColumnCount())),
                "last column name must be \"count\"");

        long count = rs.getLong("count");
        String[] tupel = new String[meta.getColumnCount() - 1];

        for (int i = 1; i <= tupel.length; i++) {
            String colVal = rs.getString(i);

            if (colVal == null) {
                tupel[i - 1] = "";
            } else {
                String[] splitted = colVal.split(":", 3);
                if (splitted.length > 0) {
                    colVal = splitted[splitted.length - 1];
                }//from   w ww . j  av  a2 s.  com

                tupel[i - 1] = colVal;
            }
        } // end for each column (except last "count" column) 

        result.addEntry(new FrequencyTable.Entry(tupel, count));

    } // end for complete result

    return result;
}

From source file:org.gsoft.admin.ScriptRunner.java

/**
 * Runs an SQL script (read in using the Reader parameter) using the
 * connection passed in//from   w ww.j av a  2 s .  c  o  m
 * 
 * @param conn
 *            - the connection to use for the script
 * @param reader
 *            - the source of the script
 * @throws SQLException
 *             if any SQL errors occur
 * @throws IOException
 *             if there is an error reading from the Reader
 */
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
    StringBuffer command = null;
    try {
        LineNumberReader lineReader = new LineNumberReader(reader);
        String line = null;
        while ((line = lineReader.readLine()) != null) {
            if (command == null) {
                command = new StringBuffer();
            }
            String trimmedLine = line.trim();
            if (trimmedLine.startsWith("--")) {
                println(trimmedLine);
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
                // Do nothing
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
                // Do nothing
            } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter())
                    || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
                command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
                command.append(" ");
                Statement statement = conn.createStatement();

                println(command);

                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        e.fillInStackTrace();
                        printlnError("Error executing: " + command);
                        printlnError(e);
                    }
                }

                if (autoCommit && !conn.getAutoCommit()) {
                    conn.commit();
                }

                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    ResultSetMetaData md = rs.getMetaData();
                    int cols = md.getColumnCount();
                    for (int i = 0; i < cols; i++) {
                        String name = md.getColumnLabel(i);
                        print(name + "\t");
                    }
                    println("");
                    while (rs.next()) {
                        for (int i = 0; i < cols; i++) {
                            String value = rs.getString(i);
                            print(value + "\t");
                        }
                        println("");
                    }
                }

                command = null;
                try {
                    statement.close();
                } catch (Exception e) {
                    // Ignore to workaround a bug in Jakarta DBCP
                }
                Thread.yield();
            } else {
                command.append(line);
                command.append(" ");
            }
        }
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } catch (IOException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } finally {
        conn.rollback();
        flush();
    }
}

From source file:JDBCExecutor.java

public void executeStatement(String sql) {

    LOG("Executing query: " + sql);
    try (Connection connection = getConnection()) {
        Statement stmt = connection.createStatement();
        LOG("\t Time taken to create statement : ");

        ResultSet rs = stmt.executeQuery(sql);
        LOG("\t Time taken to execute query : ");
        if (rs == null) {
            return;
        }// www  .j  av  a  2s. c  om

        ResultSetMetaData resultSetMetaData = rs.getMetaData();
        LOG("\t\t Time taken to get resultset metadata: ");

        boolean processedFirstRecord = false;
        while (rs.next()) {
            for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
                Object colObj = rs.getObject(i);
            }
            if (!processedFirstRecord) {
                processedFirstRecord = true;
                LOG("\t\t Processed first record : ");
            }
        }
        LOG("\t\t Processed all records : ");

        rs.close();
        LOG("\t\t Closed resultSet : ");
    } catch (SQLException e) {
        LOG("Error executing query", e);
    }
    LOG("\t Closed connection : ");
}