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:com.glaf.core.jdbc.QueryHelper.java

@SuppressWarnings("unchecked")
public List<ColumnDefinition> getColumnDefinitions(String systemName, String sql, Map<String, Object> params) {
    SqlExecutor sqlExecutor = DBUtils.replaceSQL(sql, params);
    Connection conn = null;//from   www. j a v a 2  s.  c  o  m
    PreparedStatement psmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    try {
        conn = DBConnectionFactory.getConnection(systemName);
        psmt = conn.prepareStatement(sqlExecutor.getSql());
        if (sqlExecutor.getParameter() != null) {
            List<Object> values = (List<Object>) sqlExecutor.getParameter();
            JdbcUtils.fillStatement(psmt, values);
        }
        rs = psmt.executeQuery();
        rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();
        for (int index = 1; index <= count; index++) {
            int sqlType = rsmd.getColumnType(index);
            ColumnDefinition column = new ColumnDefinition();
            column.setIndex(index);
            column.setColumnName(rsmd.getColumnName(index));
            column.setColumnLabel(rsmd.getColumnLabel(index));
            column.setJavaType(FieldType.getJavaType(sqlType));
            column.setPrecision(rsmd.getPrecision(index));
            column.setScale(rsmd.getScale(index));
            if (column.getScale() == 0 && sqlType == Types.NUMERIC) {
                column.setJavaType("Long");
            }
            column.setName(StringTools.camelStyle(column.getColumnLabel().toLowerCase()));
            columns.add(column);
        }
        return columns;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(psmt);
        JdbcUtils.close(conn);
    }
}

From source file:de.uniwue.info6.webapp.lists.ExerciseController.java

@PostConstruct
public void init() {
    if (connectionPool == null || debug) {
        importScriptError = "";
        userHasRights = false;/*from  w ww . j a  v a  2  s  .  c o m*/
        showFeedback = false;
        querySaved = false;
        usedSolutionIndex = 0;
        Boolean setEntry = null;
        Boolean setSolution = null;
        this.userRights = new UserRights();
        this.userRights.initialize();

        // init hibernate daos
        exGroupDao = new ExerciseGroupDao();
        scenarioDao = new ScenarioDao();
        exerciseDao = new ExerciseDao();
        userEntryDao = new UserEntryDao();
        userResultDao = new UserResultDao();
        solutionQueryDao = new SolutionQueryDao();

        if (!debug) {
            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            Map<String, Object> sessionMap = externalContext.getSessionMap();
            setEntry = (Boolean) sessionMap.get("show_entry");
            setSolution = (Boolean) sessionMap.get("show_solution");
            // get current scenario
            ac = SessionObject.pullFromSession();
            user = ac.getUser();
            if (user != null && user.getIsAdmin() != null) {
                userHasRights = user.getIsAdmin();
            }
            scenario = ac.getScenario();

            // set up connection pool
            connectionPool = ConnectionManager.instance();

            // get exercise id
            ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
            Map<String, String> requestParams = ec.getRequestParameterMap();
            final int id = Integer.parseInt(requestParams.get(exerciseParam));
            exercise = exerciseDao.getById(id);

        }

        if (exercise != null) {
            exerciseGroup = exGroupDao.getById(exercise.getExerciseGroup().getId());
        }

        if (exerciseGroup != null) {
            final boolean scenarioMissing = (scenario == null);
            scenario = scenarioDao.getById(exerciseGroup.getScenario().getId());
            if (scenarioMissing) {
                this.ac.setScenario(scenario);
            }
        }

        this.resultVisible = false;
        this.userResultVisible = false;
        this.feedbackVisible = false;
        this.syntaxError = false;

        if (scenario != null && exercise != null) {
            solutionQueries = new LinkedList<SqlQuery>();
            solutions = exerciseDao.getSolutions(exercise);

            if (exerciseGroup != null) {
                // try {
                // this.connectionPool.resetTables(scenario, user);
                // } catch (Exception e) {
                // LOGGER.error("COULD NOT RESET TABLES", e);
                // }

                // TODO: replace with a new table-field in exercisegroup
                if (exerciseGroup.getDescription() == null || exerciseGroup.getDescription().trim().isEmpty()) {
                    showFeedback = true;
                } else if (exerciseGroup.getDescription().trim().equals("[NO_FEEDBACK]")) {
                    showFeedback = false;
                }

                if (!exerciseGroup.getScenario().getId().equals(scenario.getId())) {
                    scenario = scenarioDao.getById(exerciseGroup.getScenario().getId());
                    userHasRights = userRights.hasViewRights(user, scenario, exerciseGroup);
                    if (!debug && userHasRights) {
                        ac.setScenario(scenario);
                    }
                }

                userHasRights = userRights.hasViewRights(user, scenario, exerciseGroup);
                if (debug) {
                    userHasRights = true;
                }

                diagramImage = scenario.getImagePath();
                if (diagramImage != null) {
                    diagramImage = RESOURCE_PATH_IMAGES + "/" + scenario.getId() + "/" + diagramImage;
                }

                // get list of sql tables
                availableTables = connectionPool.getScenarioTableNames(scenario);
                if (availableTables == null || availableTables.isEmpty()) {
                    importScriptError = connectionPool.checkIfImportScriptExists(scenario);
                }

                tableContent = new HashMap<String, String>();

                // relevant tables
                tableColumns = new HashMap<String, List<String>>();
                tableValues = new HashMap<String, List<TableEntry>>();

                if (userHasRights) {
                    for (SolutionQuery qu : solutions) {
                        SqlQuery sqlQuery = new SqlQuery(qu.getQuery());
                        try {
                            if (mainRefLink == null && sqlQuery != null) {
                                RefLink ref = sqlQuery.getRefLink();
                                mainRefLink = ref.getUrl();
                            }
                        } catch (Exception e) {
                        }
                        solutionQueries.add(sqlQuery);
                    }

                    UserEntry entry = userEntryDao.getLastUserEntry(exercise, user);

                    if (entry != null && setEntry != null && setEntry) {
                        userString = entry.getUserQuery();
                    } else if (setSolution != null && setSolution) {
                        if (entry != null) {
                            UserResult result = userResultDao.getLastUserResultFromEntry(entry);
                            SolutionQuery query = result.getSolutionQuery();
                            query = solutionQueryDao.getById(query.getId());
                            if (result != null && query != null) {
                                String query_sol = query.getQuery();
                                if (query_sol != null) {
                                    userString = query_sol;
                                }
                            }
                        } else {
                            SolutionQuery example = new SolutionQuery();
                            example.setExercise(exercise);
                            List<SolutionQuery> solutions = solutionQueryDao.findByExample(example);
                            if (solutions != null && !solutions.isEmpty()) {
                                userString = solutions.get(0).getQuery();
                            }
                        }
                    }

                    Connection connection = null;
                    try {
                        relevantTables = new HashMap<String, String>();
                        connection = connectionPool.getConnection(scenario);
                        executer = new SqlExecuter(connection, user, scenario);

                        SqlQuery selectTable = null;

                        if (availableTables != null) {
                            for (String table : availableTables) {
                                String showTableCommand = "SELECT * FROM " + table + ";";
                                selectTable = new SqlQuery(showTableCommand);
                                executer.execute(selectTable);
                                try {
                                    SqlResult result = selectTable.getResult();
                                    if (result != null) {
                                        String[][] data = result.getData();
                                        ResultSetMetaData metaData = result.getResultMetaData();
                                        List<String> clNames = new ArrayList<String>();
                                        if (metaData != null) {
                                            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                                                String name = metaData.getColumnName(i);
                                                if (name != null && !name.trim().isEmpty()) {
                                                    clNames.add(name);
                                                }
                                            }
                                            tableColumns.put(table, clNames);
                                        }
                                        if (data != null) {
                                            List<TableEntry> el = new ArrayList<TableEntry>();
                                            for (int i = 0; i < data.length; i++) {
                                                TableEntry en = new TableEntry(clNames);
                                                for (int z = 0; z < data[i].length; z++) {
                                                    en.addValue(data[i][z], z);
                                                }
                                                el.add(en);
                                            }
                                            tableValues.put(table, el);
                                        }

                                        this.tableValuesOriginal = new HashMap<String, List<TableEntry>>(
                                                tableValues);
                                        currentTableFilter = new String[tableValues.size() + 2];
                                    }
                                } catch (Exception e) {
                                    LOGGER.error("ERROR BUILDING RELEVANT TABLES", e);
                                }
                            }
                        }
                    } catch (SQLException e) {
                        String er = ExceptionUtils.getStackTrace(e);
                        if (er.length() > 500) {
                            importScriptError = er.substring(0, 500) + " [...]";
                        } else {
                            importScriptError = er;
                        }
                    } catch (Exception e) {
                        LOGGER.error("ERROR GETTING RELEVANT TABLES", e);
                    } finally {
                        if (connection != null) {
                            try {
                                connection.close();
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.oracle.OracleCDCSource.java

private Map<String, Integer> getTableSchema(SchemaAndTable schemaAndTable) throws SQLException {
    Map<String, Integer> columns = new HashMap<>();
    String query = "SELECT * FROM \"" + schemaAndTable.getSchema() + "\".\"" + schemaAndTable.getTable()
            + "\" WHERE 1 = 0";
    try (Statement schemaStatement = connection.createStatement();
            ResultSet rs = schemaStatement.executeQuery(query)) {
        ResultSetMetaData md = rs.getMetaData();
        int colCount = md.getColumnCount();
        for (int i = 1; i <= colCount; i++) {
            int colType = md.getColumnType(i);
            String colName = md.getColumnName(i);
            if (!configBean.baseConfigBean.caseSensitive) {
                colName = colName.toUpperCase();
            }//from  w w  w.  j av  a  2s .  c om
            if (colType == Types.DATE || colType == Types.TIME || colType == Types.TIMESTAMP) {
                dateTimeColumns.computeIfAbsent(schemaAndTable, k -> new HashMap<>());
                dateTimeColumns.get(schemaAndTable).put(colName, md.getColumnTypeName(i));
            }

            if (colType == Types.DECIMAL || colType == Types.NUMERIC) {
                decimalColumns.computeIfAbsent(schemaAndTable, k -> new HashMap<>());
                decimalColumns.get(schemaAndTable).put(colName,
                        new PrecisionAndScale(md.getPrecision(i), md.getScale(i)));
            }
            columns.put(md.getColumnName(i), md.getColumnType(i));
        }
    }
    return columns;
}

From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java

/**
 * @param conn/*from  www. j  av  a2 s  .co m*/
 * @param sql
 * @param includeHeaderRow
 * @return
 */
public static Vector<Object[]> query(final Connection conn, final String sql, final boolean includeHeaderRow) {
    Vector<Object[]> list = new Vector<Object[]>();
    Statement stmt = null;

    Connection connection = null;
    boolean doCloseConn = false;
    boolean doSkipConnSet = false;
    boolean isStale = true;
    int tries = 0;

    while (isStale && tries < 3) {
        try {
            if (!doSkipConnSet) {
                if (conn != null) {
                    connection = conn;

                } else if (dbConn != null) {
                    connection = dbConn;
                } else {
                    connection = DBConnection.getInstance().createConnection();
                    doCloseConn = true;
                }
            }

            if (connection == null) {
                return list;
            }

            tries++;
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData metaData = rs.getMetaData();
            int numCols = metaData.getColumnCount();
            if (includeHeaderRow) {
                Object[] colData = new Object[numCols];
                list.add(colData);
                for (int i = 0; i < numCols; i++) {
                    colData[i] = metaData.getColumnName(i + 1);
                }
            }
            while (rs.next()) {
                Object[] colData = new Object[numCols];
                list.add(colData);
                for (int i = 0; i < numCols; i++) {
                    colData[i] = rs.getObject(i + 1);
                }
            }
            rs.close();

            isStale = false;

        } catch (CommunicationsException ex) {
            connection = DBConnection.getInstance().createConnection();
            doCloseConn = true;
            doSkipConnSet = true;

        } catch (com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException e) {
            e.printStackTrace();
            if (!skipTrackExceptions) {
                edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BasicSQLUtils.class, e);
            }

        } catch (SQLException ex) {
            ex.printStackTrace();

            if (!skipTrackExceptions) {
                edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BasicSQLUtils.class, ex);
            }

        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ex) {
                }
            }
        }

        if (!isStale && connection != null && doCloseConn) {
            try {
                connection.close();
            } catch (Exception ex) {
            }
        }
    }

    return list;
}

From source file:com.glaf.dts.transform.MxTransformManager.java

@SuppressWarnings("unchecked")
protected List<Map<String, Object>> prepare(QueryDefinition query, List<Map<String, Object>> paramList) {
    logger.debug("-------------------------3 start------------------------");
    List<Map<String, Object>> resultList = new java.util.ArrayList<Map<String, Object>>();
    List<Map<String, Object>> tmpResultList = new java.util.ArrayList<Map<String, Object>>();
    Connection conn = null;//from   w  w w  .  ja  v a  2  s .co  m
    PreparedStatement psmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    try {
        Database database = databaseService.getDatabaseById(query.getDatabaseId());
        if (database != null) {
            conn = DBConnectionFactory.getConnection(database.getName());
        } else {
            conn = DBConnectionFactory.getConnection();
        }
        logger.debug("-------------------------3 connection------------------------");
        for (Map<String, Object> paramMap : paramList) {
            logger.debug("sql:" + query.getSql());
            SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(query.getSql(), paramMap);
            logger.debug("sql:" + sqlExecutor.getSql());
            psmt = conn.prepareStatement(sqlExecutor.getSql());
            if (sqlExecutor.getParameter() != null) {
                List<Object> values = (List<Object>) sqlExecutor.getParameter();
                JdbcUtils.fillStatement(psmt, values);
                logger.debug("values:" + values);
            }

            logger.debug("-------------------------3 executeQuery------------------------");
            rs = psmt.executeQuery();
            rsmd = rs.getMetaData();
            int count = rsmd.getColumnCount();
            while (rs.next()) {
                Map<String, Object> rowMap = new java.util.HashMap<String, Object>();
                for (int i = 1; i <= count; i++) {
                    String columnName = rsmd.getColumnLabel(i);
                    if (null == columnName || 0 == columnName.length()) {
                        columnName = rsmd.getColumnName(i);
                    }
                    try {
                        rowMap.put(columnName, rs.getObject(i));
                    } catch (SQLException ex) {
                        rowMap.put(columnName, rs.getString(i));
                    }
                }
                resultList.add(rowMap);
                tmpResultList.add(rowMap);
            }
            // logger.debug("resultList :" + tmpResultList);
            tmpResultList.clear();
        }

        query.setResultList(resultList);

        // logger.debug("resultList size:" + resultList.size());

        return resultList;
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(psmt);
        JdbcUtils.close(conn);
        logger.debug("-------------------------3 end------------------------");
    }
}

From source file:com.glaf.core.jdbc.QueryHelper.java

@SuppressWarnings("unchecked")
public List<ColumnDefinition> getColumns(Connection conn, String sql, Map<String, Object> paramMap) {
    if (!DBUtils.isLegalQuerySql(sql)) {
        throw new RuntimeException(" SQL statement illegal ");
    }/*from  ww w . j a  v  a2 s . c o m*/
    List<ColumnDefinition> columns = new java.util.ArrayList<ColumnDefinition>();
    PreparedStatement psmt = null;
    ResultSetMetaData rsmd = null;
    ResultSet rs = null;
    try {
        List<Object> values = null;
        if (paramMap != null) {
            SqlExecutor sqlExecutor = DBUtils.replaceSQL(sql, paramMap);
            sql = sqlExecutor.getSql();
            values = (List<Object>) sqlExecutor.getParameter();
        }

        logger.debug("sql:\n" + sql);
        logger.debug("values:" + values);

        psmt = conn.prepareStatement(sql);

        if (values != null && !values.isEmpty()) {
            JdbcUtils.fillStatement(psmt, values);
        }

        rs = psmt.executeQuery();
        rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        for (int i = 1; i <= count; i++) {
            int sqlType = rsmd.getColumnType(i);
            ColumnDefinition column = new ColumnDefinition();
            column.setColumnLabel(rsmd.getColumnLabel(i));
            column.setColumnName(rsmd.getColumnName(i));
            column.setJavaType(FieldType.getJavaType(sqlType));
            column.setPrecision(rsmd.getPrecision(i));
            column.setScale(rsmd.getScale(i));
            column.setName(StringTools.camelStyle(column.getColumnLabel().toLowerCase()));
            if (column.getScale() == 0 && sqlType == Types.NUMERIC) {
                column.setJavaType("Long");
            }
            if (!columns.contains(column)) {
                columns.add(column);
            }
            logger.debug(column.getColumnName() + " sqlType:" + sqlType + " precision:" + column.getPrecision()
                    + " scale:" + column.getScale());
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
        JdbcUtils.close(rs);
    }
    return columns;
}

From source file:com.glaf.core.jdbc.QueryHelper.java

/**
 * @param conn/*ww  w . j a  v  a 2  s.c  o m*/
 *            ?
 * @param sqlExecutor
 *            
 * @return
 */
@SuppressWarnings("unchecked")
public List<Map<String, Object>> getResultList(Connection conn, SqlExecutor sqlExecutor) {
    if (!DBUtils.isLegalQuerySql(sqlExecutor.getSql())) {
        throw new RuntimeException(" SQL statement illegal ");
    }
    List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
    PreparedStatement psmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    try {
        psmt = conn.prepareStatement(sqlExecutor.getSql());
        if (sqlExecutor.getParameter() != null) {
            List<Object> values = (List<Object>) sqlExecutor.getParameter();
            JdbcUtils.fillStatement(psmt, values);
        }

        rs = psmt.executeQuery();

        if (conf.getBoolean("useMyBatisResultHandler", false)) {

            resultList = this.getResults(rs);

        } else {

            rsmd = rs.getMetaData();

            int count = rsmd.getColumnCount();
            List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();

            for (int index = 1; index <= count; index++) {
                int sqlType = rsmd.getColumnType(index);
                ColumnDefinition column = new ColumnDefinition();
                column.setIndex(index);
                column.setColumnName(rsmd.getColumnName(index));
                column.setColumnLabel(rsmd.getColumnLabel(index));
                column.setJavaType(FieldType.getJavaType(sqlType));
                column.setPrecision(rsmd.getPrecision(index));
                column.setScale(rsmd.getScale(index));
                if (column.getScale() == 0 && sqlType == Types.NUMERIC) {
                    column.setJavaType("Long");
                }
                column.setName(StringTools.camelStyle(column.getColumnLabel().toLowerCase()));
                columns.add(column);
            }
            int startIndex = 1;
            while (rs.next() && startIndex <= 50000) {
                int index = 0;
                startIndex++;
                Map<String, Object> rowMap = new HashMap<String, Object>();
                Iterator<ColumnDefinition> iterator = columns.iterator();
                while (iterator.hasNext()) {
                    ColumnDefinition column = iterator.next();
                    String columnLabel = column.getColumnLabel();
                    String columnName = column.getColumnName();
                    if (StringUtils.isEmpty(columnName)) {
                        columnName = column.getColumnLabel();
                    }
                    columnName = columnName.toLowerCase();
                    String javaType = column.getJavaType();
                    index = index + 1;
                    if ("String".equals(javaType)) {
                        String value = rs.getString(column.getIndex());
                        if (value != null) {
                            value = value.trim();
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, value);
                        }
                    } else if ("Integer".equals(javaType)) {
                        try {
                            Integer value = rs.getInt(column.getIndex());
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, value);
                        } catch (Exception e) {
                            String str = rs.getString(column.getIndex());
                            logger.error("integer:" + str);
                            str = StringTools.replace(str, "$", "");
                            str = StringTools.replace(str, "", "");
                            str = StringTools.replace(str, ",", "");
                            NumberFormat fmt = NumberFormat.getInstance();
                            Number num = fmt.parse(str);
                            rowMap.put(columnName, num.intValue());
                            rowMap.put(columnLabel, rowMap.get(columnName));
                            logger.debug("?:" + num.intValue());
                        }
                    } else if ("Long".equals(javaType)) {
                        try {
                            Long value = rs.getLong(column.getIndex());
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, rowMap.get(columnName));
                        } catch (Exception e) {
                            String str = rs.getString(column.getIndex());
                            logger.error("long:" + str);
                            str = StringTools.replace(str, "$", "");
                            str = StringTools.replace(str, "", "");
                            str = StringTools.replace(str, ",", "");
                            NumberFormat fmt = NumberFormat.getInstance();
                            Number num = fmt.parse(str);
                            rowMap.put(columnName, num.longValue());
                            rowMap.put(columnLabel, num.longValue());
                            logger.debug("?:" + num.longValue());
                        }
                    } else if ("Double".equals(javaType)) {
                        try {
                            Double d = rs.getDouble(column.getIndex());
                            rowMap.put(columnName, d);
                            rowMap.put(columnLabel, d);
                        } catch (Exception e) {
                            String str = rs.getString(column.getIndex());
                            logger.error("double:" + str);
                            str = StringTools.replace(str, "$", "");
                            str = StringTools.replace(str, "", "");
                            str = StringTools.replace(str, ",", "");
                            NumberFormat fmt = NumberFormat.getInstance();
                            Number num = fmt.parse(str);
                            rowMap.put(columnName, num.doubleValue());
                            rowMap.put(columnLabel, num.doubleValue());
                            logger.debug("?:" + num.doubleValue());
                        }
                    } else if ("Boolean".equals(javaType)) {
                        rowMap.put(columnName, rs.getBoolean(column.getIndex()));
                        rowMap.put(columnLabel, rowMap.get(columnName));
                    } else if ("Date".equals(javaType)) {
                        rowMap.put(columnName, rs.getTimestamp(column.getIndex()));
                        rowMap.put(columnLabel, rowMap.get(columnName));
                    } else if ("Blob".equals(javaType)) {
                        // ignore
                    } else {
                        Object value = rs.getObject(column.getIndex());
                        if (value != null) {
                            if (value instanceof String) {
                                value = (String) value.toString().trim();
                            }
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, rowMap.get(columnName));
                        }
                    }
                }
                rowMap.put("startIndex", startIndex);
                resultList.add(rowMap);
            }
        }

        logger.debug(">resultList size=" + resultList.size());
        return resultList;
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
        JdbcUtils.close(rs);
    }
}

From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java

@SuppressWarnings("rawtypes")
private Object getColumnValue(ResultSet rs, ResultSetMetaData meta, int index, Class clazz) throws Exception {
    Object value = null;/*from  ww w.  j a v  a  2 s.c  o m*/

    int type = meta.getColumnType(index);
    if (clazz == String.class) {
        value = rs.getString(index);
    } else if (clazz == Integer.class) {
        value = rs.getInt(index);
    } else if (clazz == Boolean.class) {
        value = rs.getBoolean(index);
    } else if (clazz == byte[].class) {
        if (type == Types.BLOB)
            value = rs.getBlob(index);
        else
            value = rs.getBytes(index);
    } else if (clazz == Long.class) {
        value = rs.getLong(index);
    } else if (clazz == BigInteger.class) {
        value = rs.getBigDecimal(index);
    } else if (clazz == Float.class) {
        value = rs.getFloat(index);
    } else if (clazz == Double.class) {
        value = rs.getDouble(index);
    } else if (clazz == java.util.Date.class) {
        Timestamp time = rs.getTimestamp(index);
        if (time == null)
            value = null;
        else {
            value = new java.util.Date(time.getTime());
        }
    } else if (clazz == java.sql.Date.class) {
        value = rs.getDate(index);
    } else if (clazz == java.sql.Time.class) {
        value = rs.getTime(index);
    } else if (clazz == java.sql.Timestamp.class) {
        value = rs.getTimestamp(index);
    } else {
        throw new Exception("Cannote determin this column type:" + meta.getColumnName(index));
    }
    return value;
}

From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java

@Test
public void testGetMetaData() throws Exception {
    Statement statement = getConnection().createStatement();
    ResultSet rs = statement.executeQuery(SQL_EMPS);
    ResultSetMetaData metaData = rs.getMetaData();

    // When 'sql' query used, jcr adds 'jcr:path' and 'jcr:score' columns automatically.
    assertEquals(5 + Constants.META_COLUMNS.size(), metaData.getColumnCount());

    assertEquals("empno", metaData.getColumnName(1));
    assertEquals("ename", metaData.getColumnName(2));
    assertEquals("salary", metaData.getColumnName(3));
    assertEquals("hiredate", metaData.getColumnName(4));

    assertEquals("empno", metaData.getColumnLabel(1));
    assertEquals("ename", metaData.getColumnLabel(2));
    assertEquals("salary", metaData.getColumnLabel(3));
    assertEquals("hiredate", metaData.getColumnLabel(4));

    for (int i = 1; i <= metaData.getColumnCount(); i++) {
        assertFalse(metaData.isAutoIncrement(i));
        assertTrue(metaData.isCaseSensitive(i));
        assertTrue(metaData.isSearchable(i));
        assertTrue(metaData.isReadOnly(i));
        assertFalse(metaData.isWritable(i));
        assertFalse(metaData.isDefinitelyWritable(i));
    }// w w  w.  jav a2s .  co  m

    rs.close();
    statement.close();
}

From source file:org.apache.hive.jdbc.TestJdbcDriver2.java

/**
 * Validate the Metadata for the result set of a metadata getColumns call.
 *//*from   ww  w  .j  a v  a 2 s .c om*/
@Test
public void testMetaDataGetColumnsMetaData() throws SQLException {
    ResultSet rs = con.getMetaData().getColumns(null, null, "testhivejdbcdriver\\_table", null);

    ResultSetMetaData rsmd = rs.getMetaData();

    assertEquals("TABLE_CAT", rsmd.getColumnName(1));
    assertEquals(Types.VARCHAR, rsmd.getColumnType(1));
    assertEquals(Integer.MAX_VALUE, rsmd.getColumnDisplaySize(1));

    assertEquals("ORDINAL_POSITION", rsmd.getColumnName(17));
    assertEquals(Types.INTEGER, rsmd.getColumnType(17));
    assertEquals(11, rsmd.getColumnDisplaySize(17));
}