Example usage for java.sql ResultSetMetaData getColumnCount

List of usage examples for java.sql ResultSetMetaData getColumnCount

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnCount.

Prototype

int getColumnCount() throws SQLException;

Source Link

Document

Returns the number of columns in this ResultSet object.

Usage

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

/**
 * /*from   www.j a v a  2  s .c o m*/
 */
public void process() {
    boolean doQueryForCollNum = true;

    String pSQL = "INSERT INTO raw (old_id,data_provider_id,data_resource_id,resource_access_point_id, institution_code, collection_code, "
            + "catalogue_number, scientific_name, author, rank, kingdom, phylum, class, order_rank, family, genus, species, subspecies, latitude, longitude,  "
            + "lat_long_precision, max_altitude, min_altitude, altitude_precision, min_depth, max_depth, depth_precision, continent_ocean, country, state_province, county, collector_name, "
            + "locality,year, month, day, basis_of_record, identifier_name, identification_date,unit_qualifier, created, modified, deleted, collector_num) "
            + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

    String gbifSQLBase = "SELECT r.id, r.data_provider_id, r.data_resource_id, r.resource_access_point_id, r.institution_code, r.collection_code, "
            + "r.catalogue_number, r.scientific_name, r.author, r.rank, r.kingdom, r.phylum, r.class, r.order_rank, r.family, r.genus, r.species, r.subspecies, "
            + "r.latitude, r.longitude, r.lat_long_precision, r.max_altitude, r.min_altitude, r.altitude_precision, r.min_depth, r.max_depth, r.depth_precision, "
            + "r.continent_ocean, r.country, r.state_province, r.county, r.collector_name, r.locality, r.year, r.month, r.day, r.basis_of_record, r.identifier_name, "
            + "r.identification_date, r.unit_qualifier, r.created, r.modified, r.deleted";

    String gbifSQL;
    if (doQueryForCollNum) {
        gbifSQL = gbifSQLBase + " FROM raw_occurrence_record r";
    } else {
        gbifSQL = gbifSQLBase
                + ", i.identifier FROM raw_occurrence_record r, identifier_record i WHERE r.id = i.occurrence_id AND i.identifier_type = 3";
    }

    BasicSQLUtils.update(srcDBConn, "DELETE FROM raw WHERE id > 0");

    long totalRecs = BasicSQLUtils.getCount(dbConn, "SELECT COUNT(*) FROM raw_occurrence_record");
    long procRecs = 0;
    long startTime = System.currentTimeMillis();
    int secsThreshold = 0;

    PrintWriter pw = null;

    final double HRS = 1000.0 * 60.0 * 60.0;

    Statement gStmt = null;
    PreparedStatement pStmt = null;
    PreparedStatement stmt = null;

    try {
        pw = new PrintWriter("gbif.log");

        pStmt = srcDBConn.prepareStatement(pSQL);

        stmt = dbConn2.prepareStatement(
                "SELECT identifier FROM identifier_record WHERE occurrence_id = ? AND identifier_type = 3");
        //stmt.setFetchSize(Integer.MIN_VALUE);

        System.out.println("Total Records: " + totalRecs);
        pw.println("Total Records: " + totalRecs);

        gStmt = dbConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        gStmt.setFetchSize(Integer.MIN_VALUE);

        String fullSQL = gbifSQL;
        System.out.println(fullSQL);

        ResultSet gRS = gStmt.executeQuery(fullSQL);
        ResultSetMetaData rsmd = gRS.getMetaData();
        int lastColInx = rsmd.getColumnCount() + (doQueryForCollNum ? 1 : 0);

        while (gRS.next()) {
            int id = gRS.getInt(1);
            pStmt.setObject(1, id);

            for (int i = 2; i <= rsmd.getColumnCount(); i++) {
                Object obj = gRS.getObject(i);
                pStmt.setObject(i, obj);
            }

            String collNum = null;
            if (doQueryForCollNum) {
                //String tmpSQL = String.format("SELECT identifier FROM identifier_record WHERE occurrence_id = %d AND identifier_type = 3", id);
                //System.out.println(tmpSQL);
                stmt.setInt(1, id);
                ResultSet rs = stmt.executeQuery();
                if (rs.next()) {
                    collNum = rs.getString(1);
                }
                rs.close();
            } else {
                collNum = gRS.getString(lastColInx - 1);
            }

            if (StringUtils.isNotEmpty(collNum)) {
                if (collNum.length() < 256) {
                    pStmt.setString(lastColInx, collNum);

                } else {
                    pStmt.setString(lastColInx, collNum.substring(0, 255));
                }
            } else {
                pStmt.setObject(lastColInx, null);
            }

            try {
                pStmt.executeUpdate();

            } catch (Exception ex) {
                System.err.println("For ID[" + gRS.getObject(1) + "]");
                ex.printStackTrace();
                pw.print("For ID[" + gRS.getObject(1) + "] " + ex.getMessage());
                pw.flush();
            }

            procRecs++;
            if (procRecs % 10000 == 0) {
                long endTime = System.currentTimeMillis();
                long elapsedTime = endTime - startTime;

                double avergeTime = (double) elapsedTime / (double) procRecs;

                double hrsLeft = (((double) elapsedTime / (double) procRecs) * (double) totalRecs - procRecs)
                        / HRS;

                int seconds = (int) (elapsedTime / 60000.0);
                if (secsThreshold != seconds) {
                    secsThreshold = seconds;

                    String msg = String.format(
                            "Elapsed %8.2f hr.mn   Ave Time: %5.2f    Percent: %6.3f  Hours Left: %8.2f ",
                            ((double) (elapsedTime)) / HRS, avergeTime,
                            100.0 * ((double) procRecs / (double) totalRecs), hrsLeft);
                    System.out.println(msg);
                    pw.println(msg);
                    pw.flush();
                }
            }
        }

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

    } finally {
        try {
            if (gStmt != null) {
                gStmt.close();
            }
            if (pStmt != null) {
                pStmt.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            pw.close();

        } catch (Exception ex) {

        }
    }
    System.out.println("Done transferring.");
    pw.println("Done transferring.");

    /*
    int     count = 0;
    boolean cont = true;
    while (cont)
    {
    long start = System.currentTimeMillis();
            
    Statement         gStmt = null;
    PreparedStatement pStmt = null;
            
    try
    {
        gStmt = dbConn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
                
        String fullSQL = gbifSQL + String.format(" AND r.id >= %d AND r.id < %d", count, count+recordStep);
        //System.out.println(fullSQL);
                
        int               cnt  = 0;
        ResultSet         rs   = gStmt.executeQuery(fullSQL);
        ResultSetMetaData rsmd = rs.getMetaData();
                
        //System.out.println("Done with query.");
                
        pStmt = srcDBConn.prepareStatement(pSQL);
        count += recordStep;
                
        while (rs.next())
        {
            Integer id  = rs.getInt(1);
            pStmt.setInt(1, id);
                    
            for (int i=2;i<=rsmd.getColumnCount();i++)
            {
                Object obj = rs.getObject(i);
                pStmt.setObject(i, obj);
            }
                    
            pStmt.executeUpdate();
                
            cnt++;
            procRecs++;
        }
        rs.close();
                
        if (count == 0)
        {
            break;
        }
                
    } catch (Exception ex)
    {
        ex.printStackTrace();
                
    } finally 
    {
        try
        {
            if (gStmt != null)
            {
                gStmt.close();
            }
            if (pStmt != null)
            {
                pStmt.close();
            }
        } catch (Exception ex)
        {
                    
        }
    }
            
    long endTime   = System.currentTimeMillis();
    long deltaTime = endTime - start;
               
    long elapsedTime = endTime - startTime;
            
    double avergeTime = (double)elapsedTime / (double)procRecs;
            
    double hrsLeft = (((double)procRecs / (double)elapsedTime) * (double)totalRecs)  / 3600000.0;
            
    int seconds = (int)(elapsedTime / 60000.0);
    if (secsThreshold != seconds)
    {
        secsThreshold = seconds;
                
        System.out.println(String.format("Elapsed %8.2f hr.mn   Time: %5.2f  Ave Time: %5.2f    Percent: %6.3f  Hours Left: Elapsed %8.2f ", 
                ((double)(elapsedTime)) / 3600000.0, 
                ((double)(deltaTime)) / 1000.0, 
                avergeTime,
                100.0 * ((double)procRecs / (double)totalRecs),
                hrsLeft));
    }
    }
    System.out.println("Done transferring.");*/

    /*Statement uStmt = null;
    try
    {
    uStmt = srcDBConn.createStatement();
    int rv = uStmt.executeUpdate("ALTER TABLE raw ADD FULLTEXT(catalogue_number, genus, species, subspecies, collector_num)");
            
    System.out.println("Indexing rv = "+rv);
            
    } catch (Exception ex)
    {
    ex.printStackTrace();
            
    } finally 
    {
    try
    {
        if (uStmt != null)
        {
            uStmt.close();
        }
    } catch (Exception ex)
    {
        ex.printStackTrace();
    }
    }
    System.out.println("Done Indexing.");*/
}

From source file:org.jtalks.poulpe.util.databasebackup.persistence.DbTableData.java

/**
 * Returns the structure of the table in the shape of list of Table columns.
 * /*  w  ww  .ja  va  2  s .co m*/
 * @return A list of Table column elements.
 * @throws SQLException
 *             Is thrown in case any errors during work with database occur.
 */
public List<ColumnMetaData> getStructure() throws SQLException {
    List<ColumnMetaData> tableColumnList = new ArrayList<ColumnMetaData>();
    Statement stmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    Connection connection = null;
    try {
        // Get a list of defaults for the column
        // this cannot be done via ResultSetMetaData, so doing this via tableMetaData instead
        connection = dataSource.getConnection();
        DatabaseMetaData dbMetaData = connection.getMetaData();
        Map<String, String> columnDefaultValues = getColumnDefaults(dbMetaData);

        // Taking the rest of information from ResultSetMetaData object
        stmt = connection.createStatement();
        // WHERE 1 = 0 -- we don't need actual data, just a table structure, so lets make the query's result empty.
        rs = stmt.executeQuery(SELECT_FROM + tableName + " WHERE 1 = 0");
        rsmd = rs.getMetaData();
        int numberOfColumns = rsmd.getColumnCount();

        for (int i = 1; i <= numberOfColumns; i++) {
            tableColumnList.add(getColumnMetaData(rsmd, columnDefaultValues, i));
        }

    } finally {
        if (stmt != null) {
            stmt.close();
        }
        if (connection != null) {
            connection.close();
        }

    }
    return tableColumnList;
}

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

/**
 * //from  w  ww .  j ava 2s .  c o m
 */
public void processNonNullNonPlantKingdom() {
    PrintWriter pw = null;
    try {
        pw = new PrintWriter("gbif_plants_from_nonnull.log");

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

    System.out.println("----------------------- Search non-Plantae ----------------------- ");

    String gbifWhereStr = "FROM raw WHERE kingdom = '%s'";

    Vector<String> nonPlantKingdoms = new Vector<String>();
    String sqlStr = "SELECT * FROM (select kingdom, count(kingdom) as cnt from plants.raw WHERE kingdom is not null AND NOT (lower(kingdom) like '%plant%') group by kingdom) T1 ORDER BY cnt desc;";
    for (Object[] obj : BasicSQLUtils.query(sqlStr)) {
        String kingdom = (String) obj[0];
        Integer count = (Integer) obj[1];

        System.out.println(kingdom + " " + count);
        pw.println(kingdom + " " + count);
        if (!StringUtils.contains(kingdom.toLowerCase(), "plant")) {
            nonPlantKingdoms.add(kingdom);
        }
    }

    long startTime = System.currentTimeMillis();

    for (String kingdom : nonPlantKingdoms) {
        String where = String.format(gbifWhereStr, kingdom);

        String cntGBIFSQL = "SELECT COUNT(*) " + where;
        String gbifSQL = gbifSQLBase + where;

        System.out.println(cntGBIFSQL);

        long totalRecs = BasicSQLUtils.getCount(srcConn, cntGBIFSQL);
        long procRecs = 0;
        int secsThreshold = 0;

        String msg = String.format("Query: %8.2f secs",
                (double) (System.currentTimeMillis() - startTime) / 1000.0);
        System.out.println(msg);
        pw.println(msg);
        pw.flush();

        startTime = System.currentTimeMillis();

        Statement gStmt = null;
        PreparedStatement pStmt = null;

        try {
            pStmt = dstConn.prepareStatement(pSQL);

            System.out.println("Total Records: " + totalRecs);
            pw.println("Total Records: " + totalRecs);
            pw.flush();

            gStmt = srcConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
            gStmt.setFetchSize(Integer.MIN_VALUE);

            ResultSet rs = gStmt.executeQuery(gbifSQL);
            ResultSetMetaData rsmd = rs.getMetaData();

            while (rs.next()) {
                String genus = rs.getString(16);
                if (genus == null)
                    continue;

                String species = rs.getString(17);

                if (isPlant(colStmtGN, colStmtGNSP, genus, species)
                        || isPlant(colDstStmtGN, colDstStmtGNSP, genus, species)) {

                    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                        Object obj = rs.getObject(i);
                        pStmt.setObject(i, obj);
                    }

                    try {
                        pStmt.executeUpdate();

                    } catch (Exception ex) {
                        System.err.println("For Old ID[" + rs.getObject(1) + "]");
                        ex.printStackTrace();
                        pw.print("For Old ID[" + rs.getObject(1) + "] " + ex.getMessage());
                        pw.flush();
                    }

                    procRecs++;
                    if (procRecs % 10000 == 0) {
                        long endTime = System.currentTimeMillis();
                        long elapsedTime = endTime - startTime;

                        double avergeTime = (double) elapsedTime / (double) procRecs;

                        double hrsLeft = (((double) elapsedTime / (double) procRecs) * (double) totalRecs
                                - procRecs) / HRS;

                        int seconds = (int) (elapsedTime / 60000.0);
                        if (secsThreshold != seconds) {
                            secsThreshold = seconds;

                            msg = String.format(
                                    "Elapsed %8.2f hr.mn   Ave Time: %5.2f    Percent: %6.3f  Hours Left: %8.2f ",
                                    ((double) (elapsedTime)) / HRS, avergeTime,
                                    100.0 * ((double) procRecs / (double) totalRecs), hrsLeft);
                            System.out.println(msg);
                            pw.println(msg);
                            pw.flush();
                        }
                    }
                }
            }

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

        } finally {
            try {
                if (gStmt != null) {
                    gStmt.close();
                }
                if (pStmt != null) {
                    pStmt.close();
                }
                pw.close();

            } catch (Exception ex) {

            }
        }
    }
    System.out.println("Done transferring.");
    pw.println("Done transferring.");

}

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

/**
 * @param resultSet/*from ww w  .j a  v  a2 s .c  om*/
 * @param map
 */
private void pushRowData(ResultSet resultSet, Map map) throws SQLException {

    ResultSetMetaData rsMeta = resultSet.getMetaData();
    for (int idx = rsMeta.getColumnCount(); idx > 0; idx--) {
        String colName = rsMeta.getColumnName(idx);
        resultSet.updateObject(colName, map.get(colName.toLowerCase()));
    }

}

From source file:com.mmnaseri.dragonfly.fluent.impl.AbstractSelectQueryFinalizer.java

private <H> List<Map<Mapping, Object>> execute(SelectQueryExecution<E, H> selection) {
    final Connection connection = session.getConnection();
    final PreparedStatement preparedStatement;
    try {//w  w w  .j a v  a2  s. com
        final String sql = selection.getSql() + ";";
        LogFactory.getLog(Statement.class).info("Preparing statement: " + sql);
        preparedStatement = connection.prepareStatement(sql);
    } catch (SQLException e) {
        throw new DatabaseNegotiationException("Failed to get a prepared statement from the database", e);
    }
    for (ParameterDescriptor descriptor : selection.getParameters()) {
        try {
            if (descriptor.getValue() == null) {
                preparedStatement.setNull(descriptor.getIndex(), descriptor.getSqlType());
            } else {
                preparedStatement.setObject(descriptor.getIndex(), descriptor.getValue());
            }
        } catch (SQLException e) {
            throw new StatementPreparationException(
                    "Failed to prepare statement for parameter " + descriptor.getIndex(), e);
        }
    }
    final ResultSet resultSet;
    final ResultSetMetaData metaData;
    try {
        resultSet = preparedStatement.executeQuery();
    } catch (SQLException e) {
        throw new DatabaseNegotiationException("Failed to retrieve the results from the data source", e);
    }
    try {
        metaData = resultSet.getMetaData();
    } catch (SQLException e) {
        throw new DatabaseNegotiationException("Failed to get result set metadata for query", e);
    }
    final ArrayList<Map<Mapping, Object>> result = new ArrayList<Map<Mapping, Object>>();
    while (true) {
        try {
            if (!resultSet.next()) {
                break;
            }
            final HashMap<Mapping, Object> map = new HashMap<Mapping, Object>();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                map.put(new ImmutableMapping(metaData.getTableName(i), metaData.getColumnName(i),
                        metaData.getColumnLabel(i)), resultSet.getObject(i));
            }
            result.add(map);
        } catch (SQLException e) {
            throw new DatabaseNegotiationException("Failed to get the next row", e);
        }

    }
    return result;
}

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

/**
 * @param resultSet/*from  w  w  w  .  java 2 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:com.nextep.designer.sqlclient.ui.editors.SQLFullClientGUI.java

/**
 * @see com.nextep.datadesigner.gui.model.IConnector#refreshConnector()
 *///  w  ww .j  a  va  2s . com
@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:com.googlecode.fascinator.portal.services.impl.DatabaseServicesImpl.java

/**
 * Parse the results of the query into a basic Java data structure. Users
 * wanting the original result set should call getResultSet() directly
 * against the prepared statement./*from w  ww . ja v a  2  s. com*/
 * 
 * @param sql The prepared statement to get the results from.
 * @return List<Map<String, String>> A list of result rows as key/value
 *         pairs in HashMaps
 * @throws Exception if there is an error.
 */
@Override
public List<Map<String, String>> getResults(PreparedStatement sql) throws Exception {
    // Prepare variables
    List<Map<String, String>> response = new ArrayList<Map<String, String>>();
    ResultSet results = null;
    ResultSetMetaData columns = null;

    try {
        // Run the search
        results = sql.executeQuery();
        // Process the results
        columns = results.getMetaData();
        if (results.isClosed()) {
            log.error("!!! ResultSet is closed");
            return response;
        }
        while (results.next()) {
            Map<String, String> row = new HashMap<String, String>();
            for (int i = 1; i <= columns.getColumnCount(); i++) {
                // log.debug("getResults(): Storing '{}' ({}) => " +
                // results.getString(i), columns.getColumnName(i),
                // columns.getColumnLabel(i));
                row.put(columns.getColumnName(i), results.getString(i));
            }
            response.add(row);
        }
        // Finish up
        results.close();
        return response;

    } catch (SQLException ex) {
        throw new Exception("Error executing query:", ex);
    }
}

From source file:net.antidot.semantic.rdf.rdb2rdf.r2rml.core.R2RMLEngine.java

/**
 * Child_row is the logical table row derived by taking the first n columns
 * of row.//from   www.ja  v  a  2s.  c o  m
 * 
 * @param tm
 * @param n
 * @return
 * @throws SQLException
 * @throws R2RMLDataError
 */
private Map<ColumnIdentifier, byte[]> applyValueToChildRow(TermMap tm, int n)
        throws SQLException, R2RMLDataError {
    Map<ColumnIdentifier, byte[]> result = new HashMap<ColumnIdentifier, byte[]>();
    Set<ColumnIdentifier> columns = tm.getReferencedColumns();
    ResultSetMetaData referencingMetas = referencingRows.getMetaData();
    for (ColumnIdentifier column : columns) {
        int m = -1;
        for (int i = 1; i <= referencingMetas.getColumnCount(); i++) {
            ColumnIdentifier refCol = ColumnIdentifierImpl.buildFromJDBCResultSet(referencingMetas, i);
            if (refCol.equals(column)) {
                m = i;
                break;
            }
        }
        if (m == -1)
            throw new R2RMLDataError("[R2RMLEngine:applyValueToChildRow] Unknown " + column + "in child row.");
        if (m <= n) {
            byte[] value = referencingRows.getBytes(m);
            result.put(column, value);
        }
    }
    return result;
}