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:in.sc.dao.ProductHelper.java

public HashMap getProductFeatures(HashMap pMap) {
    StringBuilder sql = new StringBuilder();
    sql.append(" select * from " + pMap.get(featureTable) + " where product_id= :" + product_id);
    namedParameterJdbcTemplate = getTemplate();
    HashMap featureMap = namedParameterJdbcTemplate.query(sql.toString(), pMap,
            new ResultSetExtractor<HashMap>() {
                @Override/*from  w ww. j  a v a 2s.  c  om*/
                public HashMap extractData(ResultSet rs) throws SQLException, DataAccessException {
                    HashMap dataMap = new HashMap();
                    ResultSetMetaData rsmd = rs.getMetaData();

                    while (rs.next()) {
                        for (int i = 1; i < rsmd.getColumnCount(); i++) {
                            if (rsmd.getColumnName(i).contains("f")
                                    && !rsmd.getColumnName(i).contains("pf_id")) {
                                dataMap.put(rsmd.getColumnName(i), rs.getString(i));
                            }
                        }
                    }
                    return dataMap;
                }
            });
    return featureMap;
}

From source file:org.apache.torque.task.TorqueSQLExec.java

/**
 * print any results in the statement.//from w  w w . j a  va  2 s  .com
 *
 * @param out
 * @throws SQLException
 */
protected void printResults(PrintStream out) throws java.sql.SQLException {
    ResultSet rs = null;
    do {
        rs = statement.getResultSet();
        if (rs != null) {
            log("Processing new result set.", Project.MSG_VERBOSE);
            ResultSetMetaData md = rs.getMetaData();
            int columnCount = md.getColumnCount();
            StringBuffer line = new StringBuffer();
            if (showheaders) {
                for (int col = 1; col < columnCount; col++) {
                    line.append(md.getColumnName(col));
                    line.append(",");
                }
                line.append(md.getColumnName(columnCount));
                out.println(line);
                line.setLength(0);
            }
            while (rs.next()) {
                boolean first = true;
                for (int col = 1; col <= columnCount; col++) {
                    String columnValue = rs.getString(col);
                    if (columnValue != null) {
                        columnValue = columnValue.trim();
                    }

                    if (first) {
                        first = false;
                    } else {
                        line.append(",");
                    }
                    line.append(columnValue);
                }
                out.println(line);
                line.setLength(0);
            }
        }
    } while (statement.getMoreResults());
    out.println();
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ParametersSetterBlockServiceImpl.java

private Map<String, Integer> createTypes(JdbcTemplate jdbcTemplate, final String tableName) {
    return jdbcTemplate.execute(new StatementCallback<Map<String, Integer>>() {
        public Map<String, Integer> doInStatement(Statement stmt) throws SQLException, DataAccessException {
            ResultSet rs = stmt.executeQuery("select * from " + tableName);
            try {
                ResultSetMetaData meta = rs.getMetaData();
                Map<String, Integer> types = new HashMap<String, Integer>();
                int count = meta.getColumnCount();
                for (int i = 1; i <= count; i++) {
                    String name = meta.getColumnName(i);
                    int type = meta.getColumnType(i);
                    types.put(name, type);
                }/*from w w  w  . j av  a 2  s  .  c om*/
                return types;
            } finally {
                rs.close();
            }
        }
    });
}

From source file:org.apache.nifi.processors.standard.GenerateTableFetch.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSessionFactory sessionFactory)
        throws ProcessException {
    ProcessSession session = sessionFactory.createSession();

    FlowFile fileToProcess = null;//from   w  w  w. j a v  a2  s .co  m
    if (context.hasIncomingConnection()) {
        fileToProcess = session.get();

        if (fileToProcess == null) {
            // Incoming connection with no flow file available, do no work (see capability description)
            return;
        }
    }

    final ComponentLog logger = getLogger();

    final DBCPService dbcpService = context.getProperty(DBCP_SERVICE).asControllerService(DBCPService.class);
    final DatabaseAdapter dbAdapter = dbAdapters.get(context.getProperty(DB_TYPE).getValue());
    final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(fileToProcess)
            .getValue();
    final String columnNames = context.getProperty(COLUMN_NAMES).evaluateAttributeExpressions(fileToProcess)
            .getValue();
    final String maxValueColumnNames = context.getProperty(MAX_VALUE_COLUMN_NAMES)
            .evaluateAttributeExpressions(fileToProcess).getValue();
    final int partitionSize = context.getProperty(PARTITION_SIZE).evaluateAttributeExpressions(fileToProcess)
            .asInteger();

    final StateManager stateManager = context.getStateManager();
    final StateMap stateMap;

    try {
        stateMap = stateManager.getState(Scope.CLUSTER);
    } catch (final IOException ioe) {
        logger.error("Failed to retrieve observed maximum values from the State Manager. Will not perform "
                + "query until this is accomplished.", ioe);
        context.yield();
        return;
    }
    try {
        // Make a mutable copy of the current state property map. This will be updated by the result row callback, and eventually
        // set as the current state map (after the session has been committed)
        final Map<String, String> statePropertyMap = new HashMap<>(stateMap.toMap());

        // Build a WHERE clause with maximum-value columns (if they exist), and a list of column names that will contain MAX(<column>) aliases. The
        // executed SQL query will retrieve the count of all records after the filter(s) have been applied, as well as the new maximum values for the
        // specified columns. This allows the processor to generate the correctly partitioned SQL statements as well as to update the state with the
        // latest observed maximum values.
        String whereClause = null;
        List<String> maxValueColumnNameList = StringUtils.isEmpty(maxValueColumnNames) ? new ArrayList<>(0)
                : Arrays.asList(maxValueColumnNames.split("\\s*,\\s*"));
        List<String> maxValueClauses = new ArrayList<>(maxValueColumnNameList.size());

        String columnsClause = null;
        List<String> maxValueSelectColumns = new ArrayList<>(maxValueColumnNameList.size() + 1);
        maxValueSelectColumns.add("COUNT(*)");

        // For each maximum-value column, get a WHERE filter and a MAX(column) alias
        IntStream.range(0, maxValueColumnNameList.size()).forEach((index) -> {
            String colName = maxValueColumnNameList.get(index);
            maxValueSelectColumns.add("MAX(" + colName + ") " + colName);
            final String fullyQualifiedStateKey = getStateKey(tableName, colName);
            String maxValue = statePropertyMap.get(fullyQualifiedStateKey);
            if (StringUtils.isEmpty(maxValue) && !isDynamicTableName) {
                // If the table name is static and the fully-qualified key was not found, try just the column name
                maxValue = statePropertyMap.get(getStateKey(null, colName));
            }
            if (!StringUtils.isEmpty(maxValue)) {
                Integer type = columnTypeMap.get(fullyQualifiedStateKey);
                if (type == null && !isDynamicTableName) {
                    // If the table name is static and the fully-qualified key was not found, try just the column name
                    type = columnTypeMap.get(getStateKey(null, colName));
                }
                if (type == null) {
                    // This shouldn't happen as we are populating columnTypeMap when the processor is scheduled or when the first maximum is observed
                    throw new IllegalArgumentException("No column type found for: " + colName);
                }
                // Add a condition for the WHERE clause
                maxValueClauses.add(colName + (index == 0 ? " > " : " >= ")
                        + getLiteralByType(type, maxValue, dbAdapter.getName()));
            }
        });

        whereClause = StringUtils.join(maxValueClauses, " AND ");
        columnsClause = StringUtils.join(maxValueSelectColumns, ", ");

        // Build a SELECT query with maximum-value columns (if present)
        final String selectQuery = dbAdapter.getSelectStatement(tableName, columnsClause, whereClause, null,
                null, null);
        long rowCount = 0;

        try (final Connection con = dbcpService.getConnection(); final Statement st = con.createStatement()) {

            final Integer queryTimeout = context.getProperty(QUERY_TIMEOUT)
                    .evaluateAttributeExpressions(fileToProcess).asTimePeriod(TimeUnit.SECONDS).intValue();
            st.setQueryTimeout(queryTimeout); // timeout in seconds

            logger.debug("Executing {}", new Object[] { selectQuery });
            ResultSet resultSet;

            resultSet = st.executeQuery(selectQuery);

            if (resultSet.next()) {
                // Total row count is in the first column
                rowCount = resultSet.getLong(1);

                // Update the state map with the newly-observed maximum values
                ResultSetMetaData rsmd = resultSet.getMetaData();
                for (int i = 2; i <= rsmd.getColumnCount(); i++) {
                    //Some JDBC drivers consider the columns name and label to be very different things.
                    // Since this column has been aliased lets check the label first,
                    // if there is no label we'll use the column name.
                    String resultColumnName = (StringUtils.isNotEmpty(rsmd.getColumnLabel(i))
                            ? rsmd.getColumnLabel(i)
                            : rsmd.getColumnName(i)).toLowerCase();
                    String fullyQualifiedStateKey = getStateKey(tableName, resultColumnName);
                    String resultColumnCurrentMax = statePropertyMap.get(fullyQualifiedStateKey);
                    if (StringUtils.isEmpty(resultColumnCurrentMax) && !isDynamicTableName) {
                        // If we can't find the value at the fully-qualified key name and the table name is static, it is possible (under a previous scheme)
                        // the value has been stored under a key that is only the column name. Fall back to check the column name; either way, when a new
                        // maximum value is observed, it will be stored under the fully-qualified key from then on.
                        resultColumnCurrentMax = statePropertyMap.get(resultColumnName);
                    }

                    int type = rsmd.getColumnType(i);
                    if (isDynamicTableName) {
                        // We haven't pre-populated the column type map if the table name is dynamic, so do it here
                        columnTypeMap.put(fullyQualifiedStateKey, type);
                    }
                    try {
                        String newMaxValue = getMaxValueFromRow(resultSet, i, type, resultColumnCurrentMax,
                                dbAdapter.getName());
                        if (newMaxValue != null) {
                            statePropertyMap.put(fullyQualifiedStateKey, newMaxValue);
                        }
                    } catch (ParseException | IOException pie) {
                        // Fail the whole thing here before we start creating flow files and such
                        throw new ProcessException(pie);
                    }

                }
            } else {
                // Something is very wrong here, one row (even if count is zero) should be returned
                throw new SQLException("No rows returned from metadata query: " + selectQuery);
            }

            final long numberOfFetches = (partitionSize == 0) ? rowCount
                    : (rowCount / partitionSize) + (rowCount % partitionSize == 0 ? 0 : 1);

            // Generate SQL statements to read "pages" of data
            for (long i = 0; i < numberOfFetches; i++) {
                long limit = partitionSize == 0 ? null : partitionSize;
                long offset = partitionSize == 0 ? null : i * partitionSize;
                final String query = dbAdapter.getSelectStatement(tableName, columnNames, whereClause,
                        StringUtils.join(maxValueColumnNameList, ", "), limit, offset);
                FlowFile sqlFlowFile = (fileToProcess == null) ? session.create()
                        : session.create(fileToProcess);
                sqlFlowFile = session.write(sqlFlowFile, out -> out.write(query.getBytes()));
                session.transfer(sqlFlowFile, REL_SUCCESS);
            }

            if (fileToProcess != null) {
                session.remove(fileToProcess);
            }
        } catch (SQLException e) {
            if (fileToProcess != null) {
                logger.error("Unable to execute SQL select query {} due to {}, routing {} to failure",
                        new Object[] { selectQuery, e, fileToProcess });
                fileToProcess = session.putAttribute(fileToProcess, "generatetablefetch.sql.error",
                        e.getMessage());
                session.transfer(fileToProcess, REL_FAILURE);

            } else {
                logger.error("Unable to execute SQL select query {} due to {}",
                        new Object[] { selectQuery, e });
                throw new ProcessException(e);
            }
        }

        session.commit();
        try {
            // Update the state
            stateManager.setState(statePropertyMap, Scope.CLUSTER);
        } catch (IOException ioe) {
            logger.error(
                    "{} failed to update State Manager, observed maximum values will not be recorded. "
                            + "Also, any generated SQL statements may be duplicated.",
                    new Object[] { this, ioe });
        }
    } catch (final ProcessException pe) {
        // Log the cause of the ProcessException if it is available
        Throwable t = (pe.getCause() == null ? pe : pe.getCause());
        logger.error("Error during processing: {}", new Object[] { t.getMessage() }, t);
        session.rollback();
        context.yield();
    }
}

From source file:cosmos.sql.TestSql.java

@Test
public void testNoLimit() throws SQLException {
    loadDriverClass();/*from  w w  w  .j  ava 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() + "\"");

        final ResultSetMetaData metaData = resultSet.getMetaData();
        final int columnCount = metaData.getColumnCount();

        assertEquals(columnCount, 1);

        int resultsFound = 0;
        SortedSet<String> sets = Sets.newTreeSet();
        for (int i = 0; i < 10; i++) {
            sets.add(Integer.valueOf(i).toString());
        }
        Queue<String> values = Lists.newLinkedList(sets);

        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]");
            values.remove(onlyValue.value());
            resultsFound++;

        }

        assertEquals(resultsFound, 10);
        assertEquals(values.size(), 0);
    } finally {
        close(connection, statement);
    }
}

From source file:com.kylinolap.rest.service.QueryService.java

/**
 * @param sql//from w w  w.ja v  a 2  s  .c om
 * @param project
 * @return
 * @throws Exception
 */
private SQLResponse execute(String sql, SQLRequest sqlRequest) throws Exception {
    Connection conn = null;
    Statement stat = null;
    ResultSet resultSet = null;
    List<List<String>> results = new LinkedList<List<String>>();
    List<SelectedColumnMeta> columnMetas = new LinkedList<SelectedColumnMeta>();

    try {
        conn = getOLAPDataSource(sqlRequest.getProject()).getConnection();

        if (sqlRequest instanceof PrepareSqlRequest) {
            PreparedStatement preparedState = conn.prepareStatement(sql);

            for (int i = 0; i < ((PrepareSqlRequest) sqlRequest).getParams().length; i++) {
                setParam(preparedState, i + 1, ((PrepareSqlRequest) sqlRequest).getParams()[i]);
            }

            resultSet = preparedState.executeQuery();
        } else {
            stat = conn.createStatement();
            resultSet = stat.executeQuery(sql);
        }

        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        // Fill in selected column meta
        for (int i = 1; i <= columnCount; ++i) {
            columnMetas.add(new SelectedColumnMeta(metaData.isAutoIncrement(i), metaData.isCaseSensitive(i),
                    metaData.isSearchable(i), metaData.isCurrency(i), metaData.isNullable(i),
                    metaData.isSigned(i), metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i),
                    metaData.getColumnName(i), metaData.getSchemaName(i), metaData.getCatalogName(i),
                    metaData.getTableName(i), metaData.getPrecision(i), metaData.getScale(i),
                    metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i),
                    metaData.isWritable(i), metaData.isDefinitelyWritable(i)));
        }

        List<String> oneRow = new LinkedList<String>();

        // fill in results
        while (resultSet.next()) {
            for (int i = 0; i < columnCount; i++) {
                oneRow.add((resultSet.getString(i + 1)));
            }

            results.add(new LinkedList<String>(oneRow));
            oneRow.clear();
        }
    } catch (Exception e) {
        logger.error(e.getLocalizedMessage(), e);
        throw e;
    } finally {
        close(resultSet, stat, conn);
    }

    boolean isPartialResult = false;
    String cube = "";
    long totalScanCount = 0;
    for (OLAPContext ctx : OLAPContext.getThreadLocalContexts()) {
        isPartialResult |= ctx.storageContext.isPartialResultReturned();
        cube = ctx.cubeInstance.getName();
        totalScanCount += ctx.storageContext.getTotalScanCount();
    }

    SQLResponse response = new SQLResponse(columnMetas, results, cube, 0, false, null, isPartialResult);
    response.setTotalScanCount(totalScanCount);

    return response;
}

From source file:edu.ku.brc.specify.toycode.mexconabio.MexConvToSQLNew.java

public void convert(final String tableName, final String fileName) {
    String str = "";
    int fldLen = 0;
    int inx = 0;/* ww w.j a  va  2 s.  com*/

    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DriverManager.getConnection(
                "jdbc:mysql://localhost/mex?characterEncoding=UTF-8&autoReconnect=true", "root", "root");
        stmt = conn.createStatement();

        int[] fieldLengths = null;

        BasicSQLUtils.deleteAllRecordsFromTable(conn, tableName, SERVERTYPE.MySQL);
        Vector<Integer> types = new Vector<Integer>();
        Vector<String> names = new Vector<String>();

        String selectStr = null;
        String prepareStr = null;
        try {
            prepareStr = FileUtils.readFileToString(new File("prepare_stmt.txt"));
            selectStr = FileUtils.readFileToString(new File("select.txt"));

        } catch (IOException e) {
            e.printStackTrace();
        }

        int idInx = selectStr.indexOf("ID,");
        if (idInx == 0) {
            selectStr = selectStr.substring(3);
        }

        File file = new File("/Users/rods/Documents/" + fileName);
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        //SimpleDateFormat stf = new SimpleDateFormat("k:mm:ss");

        int rowCnt = 0;
        try {
            System.out.println(prepareStr);

            PreparedStatement pStmt = conn.prepareStatement(prepareStr);
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
            str = in.readLine();

            String[] fieldNames = StringUtils.split(str, ",");
            //String[] fieldNamesDB = StringUtils.split(selectStr, ",");

            String sql = "SELECT " + selectStr + " FROM " + tableName;
            System.out.println(sql);

            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData rsmd = rs.getMetaData();

            fieldLengths = new int[rsmd.getColumnCount()];
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                fieldLengths[i - 1] = rsmd.getPrecision(i);
                types.add(rsmd.getColumnType(i));
                names.add(rsmd.getColumnName(i));
                System.out.println((i > 1 ? fieldNames[i - 2] : "ID") + " / " + rsmd.getColumnName(i) + " - "
                        + rsmd.getPrecision(i));
            }

            int numCols = rsmd.getColumnCount();
            rs.close();

            System.out.println("Number of Fields: " + numCols);

            str = in.readLine();
            while (str != null) {
                //System.err.println(str);

                str = StringUtils.replace(str.substring(1, str.length() - 1), "\",\"", "|");

                Vector<String> fields = split(str);
                if (fields.size() != numCols) {
                    System.out.println("numCols: " + numCols + " != " + fields.size() + "fields.size()");
                    continue;
                }

                int col = 1;
                inx = 0;
                for (String fld : fields) {
                    String field = fld.trim();
                    //if (field.length() > 1)
                    //{
                    //    field = field.substring(1, field.length()-1);
                    //}
                    //if (inx > 204) break;

                    fldLen = field.length();

                    pStmt.setObject(col, null);

                    switch (types.get(inx)) {
                    case java.sql.Types.LONGVARCHAR:
                    case java.sql.Types.VARCHAR:
                    case java.sql.Types.LONGNVARCHAR: {
                        if (field.length() > 0) {
                            if (field.length() <= fieldLengths[inx]) {
                                pStmt.setString(col, field);
                            } else {
                                System.err.println(String.format("The data for `%s` (%d) is too big %d f[%s]",
                                        names.get(inx), fieldLengths[inx], field.length(), field));
                                pStmt.setString(col, null);
                            }
                        } else {
                            pStmt.setString(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.DOUBLE:
                    case java.sql.Types.FLOAT: {
                        if (StringUtils.isNotEmpty(field)) {
                            if (StringUtils.isNumeric(field)) {
                                pStmt.setDouble(col, field.length() > 0 ? Double.parseDouble(field) : null);
                            } else {
                                System.err.println(col + " Bad Number[" + field + "] ");
                                pStmt.setDate(col, null);
                            }
                        } else {
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.INTEGER: {
                        if (StringUtils.isNotEmpty(field)) {
                            if (StringUtils.isNumeric(field)) {
                                pStmt.setInt(col, field.length() > 0 ? Integer.parseInt(field) : null);
                            } else {
                                System.err.println(col + " Bad Number[" + field + "] ");
                                pStmt.setDate(col, null);
                            }
                        } else {
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.TIME: {
                        Time time = null;
                        try {
                            time = Time.valueOf(field);
                        } catch (Exception ex) {
                        }
                        pStmt.setTime(col, time);
                    }
                        break;

                    case java.sql.Types.DATE: {
                        try {
                            if (StringUtils.isNotEmpty(field)) {
                                if (StringUtils.contains(field, "/")) {
                                    field = StringUtils.replace(field, "/", "-");
                                } else if (StringUtils.contains(field, " ")) {
                                    field = StringUtils.replace(field, " ", "-");
                                }
                                pStmt.setDate(col,
                                        field.length() > 0 ? new java.sql.Date(sdf.parse(field).getTime())
                                                : null);
                            } else {
                                pStmt.setDate(col, null);
                            }
                        } catch (Exception ex) {
                            System.err.println(col + " Bad Date[" + field + "]\n" + str);
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    default: {
                        System.err.println("Error - " + types.get(inx));
                    }
                    }
                    inx++;
                    col++;
                }
                pStmt.execute();
                str = in.readLine();
                rowCnt++;
            }
            in.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        } catch (Exception e) {
            System.err.println("Row: " + rowCnt);
            System.err.println(str);
            System.err.println(inx + "  " + fieldLengths[inx] + " - Field Len: " + fldLen);
            e.printStackTrace();
        }

        /*BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        while (bis.available() > 0)
        {
        int bytesRead = bis.read(bytes);
        if (bytesRead > 0)
        {
            System.arraycopy(bytes, bytesRead, buffer, bufEndInx, bytesRead);
            bufEndInx += bytesRead;
            int inx = 0;
            while (inx < bufEndInx)
            {
                if (buffer[inx] != '\n')
                {
                    String line = 
                }
                inx++;
            }
        }
        }*/

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            stmt.close();
            conn.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.jfree.data.jdbc.JDBCCategoryDataset.java

/**
 * Populates the dataset by executing the supplied query against the
 * existing database connection.  If no connection exists then no action
 * is taken./*from www  . ja  v a 2 s.  c o  m*/
 * <p>
 * The results from the query are extracted and cached locally, thus
 * applying an upper limit on how many rows can be retrieved successfully.
 *
 * @param con  the connection.
 * @param query  the query.
 *
 * @throws SQLException if there is a problem executing the query.
 */
public void executeQuery(Connection con, String query) throws SQLException {

    Statement statement = null;
    ResultSet resultSet = null;
    try {
        statement = con.createStatement();
        resultSet = statement.executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();

        int columnCount = metaData.getColumnCount();

        if (columnCount < 2) {
            throw new SQLException("JDBCCategoryDataset.executeQuery() : insufficient columns "
                    + "returned from the database.");
        }

        // Remove any previous old data
        int i = getRowCount();
        while (--i >= 0) {
            removeRow(i);
        }

        while (resultSet.next()) {
            // first column contains the row key...
            Comparable rowKey = resultSet.getString(1);
            for (int column = 2; column <= columnCount; column++) {

                Comparable columnKey = metaData.getColumnName(column);
                int columnType = metaData.getColumnType(column);

                switch (columnType) {
                case Types.TINYINT:
                case Types.SMALLINT:
                case Types.INTEGER:
                case Types.BIGINT:
                case Types.FLOAT:
                case Types.DOUBLE:
                case Types.DECIMAL:
                case Types.NUMERIC:
                case Types.REAL: {
                    Number value = (Number) resultSet.getObject(column);
                    if (this.transpose) {
                        setValue(value, columnKey, rowKey);
                    } else {
                        setValue(value, rowKey, columnKey);
                    }
                    break;
                }
                case Types.DATE:
                case Types.TIME:
                case Types.TIMESTAMP: {
                    Date date = (Date) resultSet.getObject(column);
                    Number value = new Long(date.getTime());
                    if (this.transpose) {
                        setValue(value, columnKey, rowKey);
                    } else {
                        setValue(value, rowKey, columnKey);
                    }
                    break;
                }
                case Types.CHAR:
                case Types.VARCHAR:
                case Types.LONGVARCHAR: {
                    String string = (String) resultSet.getObject(column);
                    try {
                        Number value = Double.valueOf(string);
                        if (this.transpose) {
                            setValue(value, columnKey, rowKey);
                        } else {
                            setValue(value, rowKey, columnKey);
                        }
                    } catch (NumberFormatException e) {
                        // suppress (value defaults to null)
                    }
                    break;
                }
                default:
                    // not a value, can't use it (defaults to null)
                    break;
                }
            }
        }

        fireDatasetChanged(new DatasetChangeInfo());
        //TODO: fill in real change info
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                // report this?
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                // report this?
            }
        }
    }
}

From source file:org.ensembl.healthcheck.util.DBUtils.java

/**
 * Check all columns of a table for blank entires in columns that are marked
 * as being NOT NULL.//from w ww . jav  a  2 s  .  c  o m
 * 
 * @param con
 *            The database connection to use.
 * @param table
 *            The table to use.
 * @return The total number of blank null enums.
 */
public static int checkBlankNonNull(Connection con, String table) {

    if (con == null) {
        logger.severe("checkBlankNonNull (table): Database connection is null");
        return 0;
    }

    int blanks = 0;

    String sql = "SELECT * FROM " + table;
    ResultSet rs = null;
    Statement stmt = null;
    try {
        stmt = con.createStatement();
        rs = stmt.executeQuery(sql);
        ResultSetMetaData rsmd = rs.getMetaData();
        while (rs.next()) {
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                String columnValue = rs.getString(i);
                String columnName = rsmd.getColumnName(i);
                // should it be non-null?
                if (rsmd.isNullable(i) == ResultSetMetaData.columnNoNulls) {
                    if (columnValue == null || columnValue.equals("")) {
                        blanks++;
                        logger.warning("Found blank non-null value in column " + columnName + " in " + table);
                    }
                }
            } // for column
        }
    } catch (Exception e) {
        throw new SqlUncheckedException("Could not check for blank non-nulls", e);
    } finally {
        closeQuietly(rs);
        closeQuietly(stmt);
    }

    return blanks;

}

From source file:ResultSetIterator.java

/**
 * The positions in the returned array represent column numbers.  The 
 * values stored at each position represent the index in the 
 * <code>PropertyDescriptor[]</code> for the bean property that matches 
 * the column name.  If no bean property was found for a column, the 
 * position is set to <code>PROPERTY_NOT_FOUND</code>.
 * /*  w w w. j ava2s.  com*/
 * @param rsmd The <code>ResultSetMetaData</code> containing column 
 * information.
 * 
 * @param props The bean property descriptors.
 * 
 * @throws SQLException if a database access error occurs
 *
 * @return An int[] with column index to property index mappings.  The 0th 
 * element is meaningless because JDBC column indexing starts at 1.
 */
protected int[] mapColumnsToProperties(ResultSetMetaData rsmd, PropertyDescriptor[] props) throws SQLException {

    int cols = rsmd.getColumnCount();
    int columnToProperty[] = new int[cols + 1];
    Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);

    for (int col = 1; col <= cols; col++) {
        String columnName = rsmd.getColumnName(col);
        for (int i = 0; i < props.length; i++) {

            if (columnName.equalsIgnoreCase(props[i].getName())) {
                columnToProperty[col] = i;
                break;
            }
        }
    }

    return columnToProperty;
}