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:net.tirasa.connid.bundles.soap.wssample.ProvisioningImpl.java

@Override
public List<WSUser> query(Operand query) {
    LOG.debug("Query request received");

    List<WSUser> results = new ArrayList<WSUser>();

    Connection conn = null;/* ww w.j av a 2 s  . c om*/
    try {

        String queryString = "SELECT * FROM user" + (query == null ? "" : " WHERE " + query.toString());

        queryString = queryString.replaceAll("__NAME__", "userId").replaceAll("__UID__", "userId")
                .replaceAll("__PASSWORD__", "password");

        LOG.debug("Execute query: {}", queryString);

        if (queryString == null || queryString.length() == 0) {
            throw new SQLException("Invalid query [" + queryString + "]");
        }

        conn = connect();
        Statement statement = conn.createStatement();

        ResultSet rs = statement.executeQuery(queryString);

        ResultSetMetaData metaData = rs.getMetaData();
        LOG.debug("Metadata: {}", metaData);

        while (rs.next()) {
            WSUser user = new WSUser();

            for (int i = 0; i < metaData.getColumnCount(); i++) {
                WSAttributeValue attr = new WSAttributeValue();
                attr.setName(metaData.getColumnLabel(i + 1));
                if (StringUtils.isNotBlank(rs.getString(i + 1))) {
                    attr.addValue(rs.getString(i + 1));
                }
                if ("userId".equalsIgnoreCase(metaData.getColumnName(i + 1))) {
                    attr.setKey(true);
                    user.setAccountid(rs.getString(i + 1));
                }

                user.addAttribute(attr);
            }

            results.add(user);
        }

        LOG.debug("Retrieved users: {}", results);
    } catch (SQLException e) {
        LOG.error("Search operation failed", e);
    } finally {
        if (conn != null) {
            try {
                close(conn);
            } catch (SQLException ignore) {
                // ignore exception
            }
        }
    }

    return results;
}

From source file:org.apache.bigtop.itest.hive.TestJdbc.java

@Test
public void preparedStmtAndResultSet() throws SQLException {
    final String tableName = "bigtop_jdbc_psars_test_table";
    try (Statement stmt = conn.createStatement()) {
        stmt.execute("drop table if exists " + tableName);
        stmt.execute("create table " + tableName + " (bo boolean, ti tinyint, db double, fl float, "
                + "i int, lo bigint, sh smallint, st varchar(32))");
    }/*from w  w w.j  a  va 2  s  . c om*/

    // NOTE Hive 1.2 theoretically support binary, Date & Timestamp in JDBC, but I get errors when I
    // try to put them in the query.
    try (PreparedStatement ps = conn
            .prepareStatement("insert into " + tableName + " values (?, ?, ?, ?, ?, ?, ?, ?)")) {
        ps.setBoolean(1, true);
        ps.setByte(2, (byte) 1);
        ps.setDouble(3, 3.141592654);
        ps.setFloat(4, 3.14f);
        ps.setInt(5, 3);
        ps.setLong(6, 10L);
        ps.setShort(7, (short) 20);
        ps.setString(8, "abc");
        ps.executeUpdate();
    }

    try (PreparedStatement ps = conn.prepareStatement("insert into " + tableName + " (i, st) " + "values(?, ?)",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {
        ps.setNull(1, Types.INTEGER);
        ps.setObject(2, "mary had a little lamb");
        ps.executeUpdate();
        ps.setNull(1, Types.INTEGER, null);
        ps.setString(2, "its fleece was white as snow");
        ps.clearParameters();
        ps.setNull(1, Types.INTEGER, null);
        ps.setString(2, "its fleece was white as snow");
        ps.execute();

    }

    try (Statement stmt = conn.createStatement()) {

        ResultSet rs = stmt.executeQuery("select * from " + tableName);

        ResultSetMetaData md = rs.getMetaData();

        int colCnt = md.getColumnCount();
        LOG.debug("Column count is " + colCnt);

        for (int i = 1; i <= colCnt; i++) {
            LOG.debug("Looking at column " + i);
            String strrc = md.getColumnClassName(i);
            LOG.debug("Column class name is " + strrc);

            int intrc = md.getColumnDisplaySize(i);
            LOG.debug("Column display size is " + intrc);

            strrc = md.getColumnLabel(i);
            LOG.debug("Column label is " + strrc);

            strrc = md.getColumnName(i);
            LOG.debug("Column name is " + strrc);

            intrc = md.getColumnType(i);
            LOG.debug("Column type is " + intrc);

            strrc = md.getColumnTypeName(i);
            LOG.debug("Column type name is " + strrc);

            intrc = md.getPrecision(i);
            LOG.debug("Precision is " + intrc);

            intrc = md.getScale(i);
            LOG.debug("Scale is " + intrc);

            boolean boolrc = md.isAutoIncrement(i);
            LOG.debug("Is auto increment? " + boolrc);

            boolrc = md.isCaseSensitive(i);
            LOG.debug("Is case sensitive? " + boolrc);

            boolrc = md.isCurrency(i);
            LOG.debug("Is currency? " + boolrc);

            intrc = md.getScale(i);
            LOG.debug("Scale is " + intrc);

            intrc = md.isNullable(i);
            LOG.debug("Is nullable? " + intrc);

            boolrc = md.isReadOnly(i);
            LOG.debug("Is read only? " + boolrc);

        }

        while (rs.next()) {
            LOG.debug("bo = " + rs.getBoolean(1));
            LOG.debug("bo = " + rs.getBoolean("bo"));
            LOG.debug("ti = " + rs.getByte(2));
            LOG.debug("ti = " + rs.getByte("ti"));
            LOG.debug("db = " + rs.getDouble(3));
            LOG.debug("db = " + rs.getDouble("db"));
            LOG.debug("fl = " + rs.getFloat(4));
            LOG.debug("fl = " + rs.getFloat("fl"));
            LOG.debug("i = " + rs.getInt(5));
            LOG.debug("i = " + rs.getInt("i"));
            LOG.debug("lo = " + rs.getLong(6));
            LOG.debug("lo = " + rs.getLong("lo"));
            LOG.debug("sh = " + rs.getShort(7));
            LOG.debug("sh = " + rs.getShort("sh"));
            LOG.debug("st = " + rs.getString(8));
            LOG.debug("st = " + rs.getString("st"));
            LOG.debug("tm = " + rs.getObject(8));
            LOG.debug("tm = " + rs.getObject("st"));
            LOG.debug("tm was null " + rs.wasNull());
        }
        LOG.debug("bo is column " + rs.findColumn("bo"));

        int intrc = rs.getConcurrency();
        LOG.debug("concurrency " + intrc);

        intrc = rs.getFetchDirection();
        LOG.debug("fetch direction " + intrc);

        intrc = rs.getType();
        LOG.debug("type " + intrc);

        Statement copy = rs.getStatement();

        SQLWarning warning = rs.getWarnings();
        while (warning != null) {
            LOG.debug("Found a warning: " + warning.getMessage());
            warning = warning.getNextWarning();
        }
        rs.clearWarnings();
    }
}

From source file:i5.las2peer.services.loadStoreGraphService.LoadStoreGraphService.java

/**
 * /*from   w  w w .  j  a va 2  s. c  o m*/
 * getGraphList
 * 
 * 
 * @return HttpResponse
 * 
 */
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internalError"),
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "graphListAsJsonArray"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "noGraphExists") })
@ApiOperation(value = "getGraphList", notes = "")
public HttpResponse getGraphList() {

    String result = "";
    String columnName = "";
    String selectquery = "";
    int columnCount = 0;
    Connection conn = null;
    PreparedStatement stmnt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    JSONObject ro = null;
    JSONArray graphList = new JSONArray();
    try {
        // get connection from connection pool
        conn = dbm.getConnection();
        selectquery = "SELECT graphId, description FROM graphs;";
        // prepare statement
        stmnt = conn.prepareStatement(selectquery);

        // retrieve result set
        rs = stmnt.executeQuery();
        rsmd = (ResultSetMetaData) rs.getMetaData();
        columnCount = rsmd.getColumnCount();

        // process result set
        while (rs.next()) {
            ro = new JSONObject();
            for (int i = 1; i <= columnCount; i++) {
                result = rs.getString(i);
                columnName = rsmd.getColumnName(i);
                // setup resulting JSON Object
                ro.put(columnName, result);

            }
            graphList.add(ro);
        }
        if (graphList.isEmpty()) {
            String er = "No results";
            HttpResponse noGraphExists = new HttpResponse(er, HttpURLConnection.HTTP_NOT_FOUND);
            return noGraphExists;
        } else {
            // return HTTP Response on success
            HttpResponse graphListAsJsonArray = new HttpResponse(graphList.toJSONString(),
                    HttpURLConnection.HTTP_OK);
            return graphListAsJsonArray;
        }
    } catch (Exception e) {
        String er = "Internal error: " + e.getMessage();
        HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
        return internalError;
    } finally {
        // free resources
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
        if (stmnt != null) {
            try {
                stmnt.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
    }

}

From source file:org.apache.camel.component.jdbc.JdbcProducer.java

/**
 * Sets the result from the ResultSet to the Exchange as its OUT body.
 *//*from www.j  a  va 2  s .c  om*/
protected void setResultSet(Exchange exchange, ResultSet rs) throws SQLException {
    ResultSetMetaData meta = rs.getMetaData();

    // should we use jdbc4 or jdbc3 semantics
    boolean jdbc4 = getEndpoint().isUseJDBC4ColumnNameAndLabelSemantics();

    int count = meta.getColumnCount();
    List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
    int rowNumber = 0;
    while (rs.next() && (readSize == 0 || rowNumber < readSize)) {
        Map<String, Object> row = new HashMap<String, Object>();
        for (int i = 0; i < count; i++) {
            int columnNumber = i + 1;
            // use column label to get the name as it also handled SQL SELECT aliases
            String columnName;
            if (jdbc4) {
                // jdbc 4 should use label to get the name
                columnName = meta.getColumnLabel(columnNumber);
            } else {
                // jdbc 3 uses the label or name to get the name
                try {
                    columnName = meta.getColumnLabel(columnNumber);
                } catch (SQLException e) {
                    columnName = meta.getColumnName(columnNumber);
                }
            }
            // use index based which should be faster
            row.put(columnName, rs.getObject(columnNumber));
        }
        data.add(row);
        rowNumber++;
    }
    exchange.getOut().setHeader(JdbcConstants.JDBC_ROW_COUNT, rowNumber);
    exchange.getOut().setBody(data);
}

From source file:de.innovationgate.webgate.api.jdbc.custom.JDBCSource.java

/**
 * @param resultSet//w w w . j a v  a2  s  .co  m
 * @return
 */
private Map extractRowData(ResultSet resultSet) throws SQLException {

    Map row = new HashMap();
    ResultSetMetaData rsMeta = resultSet.getMetaData();
    for (int idx = rsMeta.getColumnCount(); idx > 0; idx--) {
        Object value = resultSet.getObject(idx);
        row.put(rsMeta.getColumnLabel(idx).toLowerCase(), value);
        row.put(rsMeta.getColumnName(idx).toLowerCase(), value);
    }
    return row;

}

From source file:org.connid.bundles.soap.wssample.ProvisioningImpl.java

@Override
public List<WSUser> query(Operand query) {
    LOG.debug("Query request received");

    List<WSUser> results = new ArrayList<WSUser>();

    Connection conn = null;// w w w  .  j av a 2 s  . c o  m
    try {

        String queryString = "SELECT * FROM user" + (query == null ? "" : " WHERE " + query.toString());

        queryString = queryString.replaceAll("__NAME__", "userId").replaceAll("__UID__", "userId")
                .replaceAll("__PASSWORD__", "password");

        LOG.debug("Execute query: {}", queryString);

        if (queryString == null || queryString.length() == 0) {
            throw new SQLException("Invalid query [" + queryString + "]");
        }

        conn = connect();
        Statement statement = conn.createStatement();

        ResultSet rs = statement.executeQuery(queryString);

        ResultSetMetaData metaData = rs.getMetaData();
        LOG.debug("Metadata: {}", metaData);

        while (rs.next()) {
            WSUser user = new WSUser();

            for (int i = 0; i < metaData.getColumnCount(); i++) {
                WSAttributeValue attr = new WSAttributeValue();
                attr.setName(metaData.getColumnLabel(i + 1));
                if (StringUtils.isNotBlank(rs.getString(i + 1))) {
                    attr.setValues(Collections.singletonList(rs.getString(i + 1)));
                }
                if ("userId".equalsIgnoreCase(metaData.getColumnName(i + 1))) {
                    attr.setKey(true);
                    user.setAccountid(rs.getString(i + 1));
                }

                user.addAttribute(attr);
            }

            results.add(user);
        }

        LOG.debug("Retrieved users: {}", results);
    } catch (SQLException e) {
        LOG.error("Search operation failed", e);
    } finally {
        if (conn != null) {
            try {
                close(conn);
            } catch (SQLException ignore) {
                // ignore exception
            }
        }
    }

    return results;
}

From source file:common.dao.impl.BaseDAOImpl.java

public List<Map<String, Object>> callQueryProcedure(final String sql, final Object[] params) {
    logger.debug("start to call procedure" + sql + ", params is " + params);
    final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    getCurrentSession().doWork(new Work() {
        public void execute(Connection conn) throws SQLException {
            CallableStatement cs = conn.prepareCall(sql);
            if (params != null) {
                logger.debug("params is not null it's members is " + Arrays.asList(params));
                for (int i = 0; i < params.length; i++) {
                    cs.setObject(i + 1, params[i]);
                }//from   ww w  . j av  a2 s.c  om
            } else
                logger.debug("params is null");
            ResultSet rs = cs.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int colCount = metaData.getColumnCount();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (int i = 1; i <= colCount; i++) {
                    String colName = metaData.getColumnName(i);
                    map.put(colName, rs.getObject(colName));
                }
                result.add(map);
            }
            rs.close();
            cs.close();
        }
    });
    return result;
}

From source file:com.chiorichan.database.DatabaseEngine.java

public LinkedHashMap<String, Object> selectOne(String table, List<String> keys, List<? extends Object> values)
        throws SQLException {
    if (con == null)
        throw new SQLException("The SQL connection is closed or was never opened.");

    if (isNull(keys) || isNull(values)) {
        Loader.getLogger().warning("[DB ERROR] Either keys array or values array equals null!\n");
        return null;
    }/*  w  w  w.  j  av a 2 s.c  o  m*/

    if (keys.size() != values.size()) {
        System.err.print("[DB ERROR] Keys array and values array must match in length!\n");
        return null;
    }

    LinkedHashMap<String, Object> result = new LinkedHashMap<String, Object>();

    String where = "";

    if (keys.size() > 0 && values.size() > 0) {
        int x = 0;
        String prefix = "";
        for (String s : keys) {
            where += prefix + "`" + s + "` = '" + values.get(x) + "'";
            x++;
            prefix = " AND ";
        }
    }

    ResultSet rs = query("SELECT * FROM `" + table + "` WHERE " + where + " LIMIT 1;");

    if (rs != null && getRowCount(rs) > 0) {
        try {
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();

            do {
                for (int i = 1; i < columnCount + 1; i++) {
                    result.put(rsmd.getColumnName(i), rs.getObject(i));
                }
            } while (rs.next());

            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return null;
}

From source file:com.nextep.designer.sqlclient.ui.editors.SQLFullClientGUI.java

/**
 * @see com.nextep.datadesigner.gui.model.IConnector#refreshConnector()
 *///from  ww  w . j a v  a  2 s . co  m
@Override
public void refreshConnector() {
    // Clearing current table columns
    // clearSQLView();

    final ISQLScript script = (ISQLScript) getModel();
    if (script.getSql() == null || "".equals(script.getSql())) {
        return;
    }
    try {
        // sqlText.add("select * from " + o.getName());
        // sqlText.select(sqlText.getItemCount()-1);
        // Creating result table
        final CTabItem sqlItem = new CTabItem(sqlFolder, SWT.NONE);
        Composite resultPane = new Composite(sqlFolder, SWT.NONE);
        final Table sqlView = new Table(resultPane, SWT.FULL_SELECTION | SWT.BORDER);
        final NextepTableEditor editor = NextepTableEditor.handle(sqlView);
        CoolBar statsBar = new CoolBar(resultPane, SWT.NONE);
        statsBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        final CoolItem rowsItem = new CoolItem(statsBar, SWT.NONE);
        rowsItem.setSize(rowsItem.computeSize(100, 20));
        final Label rowsCount = new Label(statsBar, SWT.NONE);
        rowsItem.setControl(rowsCount);
        final CoolItem timeItem = new CoolItem(statsBar, SWT.NONE);
        final Label timeLabel = new Label(statsBar, SWT.NONE);
        timeItem.setControl(timeLabel);
        timeItem.setSize(timeItem.computeSize(200, 20));
        sqlView.setHeaderVisible(true);
        sqlView.setLinesVisible(true);
        sqlView.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1));
        resultPane.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1));
        GridLayout grid = new GridLayout();
        grid.marginBottom = grid.marginHeight = grid.marginLeft = grid.marginRight = grid.marginTop = grid.marginWidth = 0;
        resultPane.setLayout(grid);
        sqlItem.setControl(resultPane);
        final Listener sortListener = new SortListener(sqlView);
        final String query = formatQuery(script.getSql());
        final int queryLen = query.length();
        sqlItem.setText(queryLen < 30 ? query : query.substring(0, 30) + "...");
        sqlItem.setToolTipText(query);
        sqlFolder.setSelection(sqlItem);
        final List<ICommand> bufferedCommands = new ArrayList<ICommand>();
        // Initializing lines
        Job refreshJob = new Job("Fetching SQL data...") {

            @Override
            protected IStatus run(IProgressMonitor monitor) {
                Statement s = null;
                ResultSet r = null;
                try {
                    s = connection.createStatement();
                    final Date startDate = new Date();
                    final boolean isResultSet = s.execute(query);
                    final Date afterExecDate = new Date();

                    if (!isResultSet) {
                        final int updates = s.getUpdateCount();
                        bufferedCommands.add(new ICommand() {

                            @Override
                            public String getName() {
                                return null;
                            }

                            @Override
                            public Object execute(Object... parameters) {
                                if (sqlView != null && !sqlView.isDisposed()) {
                                    TableColumn c = new TableColumn(sqlView, SWT.NONE);
                                    c.setText(SQLClientMessages.getString("sql.result"));
                                    c.setWidth(300);
                                    c.addListener(SWT.Selection, sortListener);
                                    if (updates > 0) {
                                        final TableItem i = new TableItem(sqlView, SWT.NONE);
                                        i.setText(MessageFormat.format(
                                                SQLClientMessages.getString("sql.updatedRows"), updates));
                                    } else {
                                        final TableItem i = new TableItem(sqlView, SWT.NONE);
                                        i.setText(SQLClientMessages.getString("sql.queryOk"));
                                    }
                                }
                                return null;
                            }
                        });
                        syncProcessCommands(bufferedCommands);
                        return Status.OK_STATUS;
                    }
                    r = s.getResultSet();

                    // Initializing columns
                    final ResultSetMetaData md = r.getMetaData();
                    // Initializing sizing table
                    final int[] colMaxWidth = new int[md.getColumnCount() + 1];
                    for (int i = 1; i <= md.getColumnCount(); i++) {
                        final int index = i;
                        final String colName = md.getColumnName(index);
                        // final int colPrecision = md.getPrecision(index);
                        final int colType = md.getColumnType(index);
                        final int colIndex = i - 1;

                        bufferedCommands.add(new ICommand() {

                            @Override
                            public String getName() {
                                return null;
                            }

                            @Override
                            public Object execute(Object... parameters) {
                                if (!sqlView.isDisposed()) {
                                    TableColumn c = new TableColumn(sqlView, SWT.NONE);
                                    c.addListener(SWT.Selection, sortListener);
                                    c.setText(colName);
                                    c.setWidth(colName.length() * 8);
                                    colMaxWidth[colIndex] = c.getWidth();
                                    c.setData(COL_TYPE, colType);
                                    TextColumnEditor.handle(editor, colIndex, ChangeEvent.CUSTOM_1,
                                            new IEventListener() {

                                                @Override
                                                public void handleEvent(ChangeEvent event, IObservable source,
                                                        Object data) {
                                                }
                                            });
                                }
                                return null;
                            }
                        });
                    }
                    final ResultSet rset = r;
                    int rows = 0;
                    final long execTime = afterExecDate.getTime() - startDate.getTime();
                    bufferedCommands.add(new ICommand() {

                        @Override
                        public String getName() {
                            return null;
                        }

                        @Override
                        public Object execute(Object... parameters) {
                            timeLabel.setText(MessageFormat
                                    .format(SQLClientMessages.getString("sql.executionTime"), execTime));
                            return null;
                        }
                    });
                    syncProcessCommands(bufferedCommands);
                    while (r.next()) {
                        rows++;
                        // Handling cancellation while fetching SQL lines
                        if (monitor.isCanceled()) {
                            return Status.CANCEL_STATUS;
                        }
                        final String[] colValues = new String[md.getColumnCount()];
                        final Collection<Integer> nullCols = new ArrayList<Integer>();
                        for (int i = 1; i <= md.getColumnCount(); i++) {
                            Object val = null;
                            try {
                                val = rset.getObject(i);
                            } catch (SQLException e) {
                                LOGGER.error("Error while fetching column value : " + e.getMessage(), e);
                                val = e.getMessage();
                            }
                            final String strVal = strVal(val);
                            colValues[i - 1] = strVal;
                            // Building list of null columns
                            if (val == null) {
                                nullCols.add(i - 1);
                            }
                            // Updating max sizes
                            final int colWidth = colMaxWidth[i - 1];
                            if (strVal.length() * 8 > colWidth) {
                                colMaxWidth[i - 1] = strVal.length() * 8;
                            }
                        }
                        // Adding the row as a command
                        bufferedCommands.add(buildAddRowCommand(colValues, sqlView, nullCols));
                        // Flushing to display every N lines
                        if (bufferedCommands.size() > MAX_ROWS_BEFORE_REFRESH) {
                            bufferedCommands.add(buildAdjustWidthCommand(sqlView, colMaxWidth));
                            syncProcessCommands(bufferedCommands);
                        }
                    }
                    // Flushing any left row
                    bufferedCommands.add(buildAdjustWidthCommand(sqlView, colMaxWidth));

                    final Date afterFetchDate = new Date();
                    final int nbRows = rows;
                    bufferedCommands.add(new ICommand() {

                        @Override
                        public String getName() {
                            // TODO Auto-generated method stub
                            return null;
                        }

                        @Override
                        public Object execute(Object... parameters) {
                            long fetchTime = afterFetchDate.getTime() - afterExecDate.getTime();
                            timeLabel.setText(
                                    MessageFormat.format(SQLClientMessages.getString("sql.executionFetchTime"),
                                            execTime, fetchTime));
                            rowsCount.setText(MessageFormat
                                    .format(SQLClientMessages.getString("sql.fetchedRows"), nbRows));
                            return null;
                        }
                    });
                    syncProcessCommands(bufferedCommands);
                } catch (final SQLException e) {
                    PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {

                        @Override
                        public void run() {
                            if (!sqlView.isDisposed()) {
                                sqlView.removeAll();
                                for (TableColumn c : sqlView.getColumns()) {
                                    c.dispose();
                                }
                                TableColumn c = new TableColumn(sqlView, SWT.NONE);
                                c.setText("SQL Exception " + e.getErrorCode());
                                c.setWidth(300);
                                TableItem i = new TableItem(sqlView, SWT.NONE);
                                i.setText(e.getMessage());
                            }

                        }
                    });
                    // throw new ErrorException(e);
                } finally {
                    try {
                        if (r != null) {// && !r.isClosed()) {
                            r.close();
                        }
                        if (s != null) { // && !s.isClosed()) {
                            s.close();
                        }
                    } catch (SQLException e) {
                        throw new ErrorException(e);
                    } finally {
                        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {

                            @Override
                            public void run() {
                                // If the user has closed his SQL Query editor, we will
                                // fall here (exception) with a disposed button
                                if (runSQLButton != null && !runSQLButton.isDisposed()) {
                                    runSQLButton.setEnabled(true);
                                }
                            }
                        });
                    }
                }

                return Status.OK_STATUS;
            }
        };
        runSQLButton.setEnabled(false);
        refreshJob.schedule();

        // } catch(SQLException e) {
        // throw new ErrorException(e);
    } finally {
        // try {
        // if(stmt != null && !stmt.isClosed()) {
        // stmt.close();
        // }
        // if(rset != null && !rset.isClosed()) {
        // rset.close();
        // }
        // } catch(SQLException e) {
        // throw new ErrorException(e);
        // }
    }
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java

public List<ColumnVO> getColumnsMetaData(String sql) throws Exception {
    Exception error = null;/*from  ww  w  . jav  a  2  s .co  m*/

    List<ColumnVO> tableColumns = new LinkedList<ColumnVO>();

    Connection connection = null;
    PreparedStatement preparedStmnt = null;

    try {
        DataSource dataSource = poolDataSources.get(schemaId);
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        preparedStmnt = connection.prepareStatement(sql);
        ResultSet rs = preparedStmnt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String columnName = rsmd.getColumnName(i);
            String columnType = rsmd.getColumnTypeName(i);
            int columnSqlType = rsmd.getColumnType(i);
            int columnLength = rsmd.getColumnDisplaySize(i);
            int columnPrecision = rsmd.getPrecision(i);

            ColumnVO column = new ColumnVO();
            column.setNameOnTable(columnName);
            column.setType(columnType);
            column.setSqlType(columnSqlType);
            column.setLength(columnLength);
            column.setPrecision(columnPrecision);
            column.setInTable(true);

            tableColumns.add(column);
        }
    } catch (SQLException e) {
        error = e;
    } finally {
        if (preparedStmnt != null) {
            try {
                preparedStmnt.close();
            } catch (SQLException se2) {
                log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage()));
            }
        }
        if (connection != null) {
            try {
                if (error != null) {
                    connection.rollback();
                }
            } catch (SQLException se) {
                log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage()));
            }
            try {
                connection.close();
            } catch (SQLException se) {
                log.warn("Se produjo un error al intentar cerrar la conexin: "
                        .concat(se.getLocalizedMessage()));
            }
        }
    }
    if (error != null) {
        throw error;
    }
    return tableColumns;
}