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:eionet.cr.dao.virtuoso.VirtuosoStagingDatabaseDAO.java

@Override
public Set<String> prepareStatement(String sql, String dbName) throws DAOException {

    if (StringUtils.isBlank(sql)) {
        throw new IllegalArgumentException("The given SQL statement must not be blank!");
    }//www.  j  a v  a  2  s  .c o  m

    LinkedHashSet<String> result = new LinkedHashSet<String>();

    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
        conn = getSQLConnection(dbName);
        pstmt = SQLUtil.prepareStatement(sql, null, conn);
        ResultSetMetaData metaData = pstmt.getMetaData();
        int colCount = metaData.getColumnCount();
        for (int i = 1; i <= colCount; i++) {
            String colName = metaData.getColumnName(i);
            result.add(colName);
        }
    } catch (SQLException e) {
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(pstmt);
        SQLUtil.close(conn);
    }

    return result;
}

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

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

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

        int[] fieldLengths = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    fldLen = field.length();

                    pStmt.setObject(col, null);

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

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

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

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

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

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

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

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

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

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

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

public void testSearch() {
    Statement stmt = null;//from www . j a  v  a2  s .  c o m

    String querystr = "Andrew AND Bentley AND Apogon AND angustatus";
    String term = "contents";
    try {
        stmt = srcDBConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

        if (analyzer == null) {
            analyzer = new StandardAnalyzer(Version.LUCENE_36);
        }
        reader = IndexReader.open(FSDirectory.open(INDEX_DIR), true);

        long startTime = System.currentTimeMillis();
        Query q = new QueryParser(Version.LUCENE_36, term, analyzer).parse(querystr);
        int hitsPerPage = 10;
        searcher = new IndexSearcher(reader);
        TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
        searcher.search(q, collector);
        ScoreDoc[] hits = collector.topDocs().scoreDocs;
        System.out.println("Found " + hits.length + " hits.");
        for (int i = 0; i < hits.length; ++i) {
            int docId = hits[i].doc;
            Document d = searcher.doc(docId);
            System.out.println((i + 1) + ". " + d.get("id"));

            String id = d.get("id");

            ResultSet rs = stmt.executeQuery(
                    "SELECT id, catalogue_number, genus, species, collector_num, collector_name, year, month, day FROM raw WHERE id = "
                            + id);
            ResultSetMetaData rsmd = rs.getMetaData();

            while (rs.next()) {
                for (int j = 1; j <= rsmd.getColumnCount(); j++) {
                    System.out.print(rs.getObject(j) + "\t");
                }
                System.out.println();
            }
            rs.close();
        }
        System.out.println(String.format("Time: %8.2f", (System.currentTimeMillis() - startTime) / 1000.0));
        searcher.close();
        reader.close();
        analyzer.close();

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

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

    } catch (ParseException e) {
        e.printStackTrace();
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

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;//from w  w  w . ja v  a2s.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.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:ResultSetIterator.java

/**
 * Convert a <code>ResultSet</code> row into an <code>Object[]</code>.
 * This implementation copies column values into the array in the same 
 * order they're returned from the <code>ResultSet</code>.  Array elements
 * will be set to <code>null</code> if the column was SQL NULL.
 *
 * @see org.apache.commons.dbutils.RowProcessor#toArray(java.sql.ResultSet)
 *///from   w  w w  .j a  v a2  s.c  o m
public Object[] toArray(ResultSet rs) throws SQLException {
    ResultSetMetaData meta = rs.getMetaData();
    int cols = meta.getColumnCount();
    Object[] result = new Object[cols];

    for (int i = 0; i < cols; i++) {
        result[i] = rs.getObject(i + 1);
    }

    return result;
}

From source file:ResultSetIterator.java

/**
 * Convert a <code>ResultSet</code> row into a <code>Map</code>.  This 
 * implementation returns a <code>Map</code> with case insensitive column
 * names as keys.  Calls to <code>map.get("COL")</code> and 
 * <code>map.get("col")</code> return the same value.
 * @see org.apache.commons.dbutils.RowProcessor#toMap(java.sql.ResultSet)
 *///from w  w w .j  av  a  2  s .  com
public Map toMap(ResultSet rs) throws SQLException {
    Map result = new CaseInsensitiveHashMap();
    ResultSetMetaData rsmd = rs.getMetaData();
    int cols = rsmd.getColumnCount();

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

    return result;
}

From source file:com.tascape.reactor.report.MySqlBaseBean.java

public void importJson(JSONObject json) throws NamingException, SQLException {
    JSONObject sr = json.getJSONObject("suite_result");
    String srid = sr.getString(SuiteResult.SUITE_RESULT_ID);
    LOG.debug("srid {}", srid);

    try (Connection conn = this.getConnection()) {
        String sql = "SELECT * FROM " + SuiteResult.TABLE_NAME + " WHERE " + SuiteResult.SUITE_RESULT_ID
                + " = ?;";
        PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
        stmt.setString(1, srid);/* w  w w  .  j  a  va2 s  . c om*/
        ResultSet rs = stmt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        if (rs.first()) {
            LOG.debug("already imported {}", srid);
            return;
        }
        rs.moveToInsertRow();
        for (int col = 1; col <= rsmd.getColumnCount(); col++) {
            String cn = rsmd.getColumnLabel(col);
            rs.updateObject(cn, sr.opt(cn));
        }
        rs.insertRow();
        rs.last();
        rs.updateRow();
        LOG.debug("sr imported");
    }

    try (Connection conn = this.getConnection()) {
        String sql = "SELECT * FROM " + SuiteProperty.TABLE_NAME + " WHERE " + SuiteProperty.SUITE_RESULT_ID
                + " = ?;";
        PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
        stmt.setString(1, srid);
        ResultSet rs = stmt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();

        JSONArray sps = sr.getJSONArray("suite_properties");
        int len = sps.length();
        for (int i = 0; i < len; i++) {
            rs.moveToInsertRow();
            JSONObject tr = sps.getJSONObject(i);
            for (int col = 1; col <= rsmd.getColumnCount(); col++) {
                String cn = rsmd.getColumnLabel(col);
                if (SuiteProperty.SUITE_PROPERTY_ID.equals(cn)) {
                    continue;
                }
                rs.updateObject(cn, tr.get(cn));
            }
            rs.insertRow();
            rs.last();
            rs.updateRow();
        }
        LOG.debug("sps imported");
    }

    JSONArray trs = sr.getJSONArray("case_results");
    int len = trs.length();

    try (Connection conn = this.getConnection()) {
        String sql = String.format("SELECT * FROM %s WHERE %s=? AND %s=? AND %s=? AND %s=? AND %s=?;",
                TaskCase.TABLE_NAME, TaskCase.SUITE_CLASS, TaskCase.CASE_CLASS, TaskCase.CASE_METHOD,
                TaskCase.CASE_DATA_INFO, TaskCase.CASE_DATA);
        PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
        stmt.setMaxRows(1);
        for (int i = 0; i < len; i++) {
            JSONObject tr = trs.getJSONObject(i);
            stmt.setString(1, tr.getString(TaskCase.SUITE_CLASS));
            stmt.setString(2, tr.getString(TaskCase.CASE_CLASS));
            stmt.setString(3, tr.getString(TaskCase.CASE_METHOD));
            stmt.setString(4, tr.getString(TaskCase.CASE_DATA_INFO));
            stmt.setString(5, tr.getString(TaskCase.CASE_DATA));
            ResultSet rs = stmt.executeQuery();
            if (!rs.first()) {
                rs.moveToInsertRow();
                rs.updateString(TaskCase.SUITE_CLASS, tr.getString(TaskCase.SUITE_CLASS));
                rs.updateString(TaskCase.CASE_CLASS, tr.getString(TaskCase.CASE_CLASS));
                rs.updateString(TaskCase.CASE_METHOD, tr.getString(TaskCase.CASE_METHOD));
                rs.updateString(TaskCase.CASE_DATA_INFO, tr.getString(TaskCase.CASE_DATA_INFO));
                rs.updateString(TaskCase.CASE_DATA, tr.getString(TaskCase.CASE_DATA));
                rs.insertRow();
                rs.last();
                rs.updateRow();
                rs = stmt.executeQuery();
                rs.first();
            }
            tr.put(TaskCase.TASK_CASE_ID, rs.getLong(TaskCase.TASK_CASE_ID));
        }
        LOG.debug("tcid updated");
    }

    try (Connection conn = this.getConnection()) {
        String sql = "SELECT * FROM " + CaseResult.TABLE_NAME + " WHERE " + CaseResult.SUITE_RESULT + " = ?;";
        PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
        stmt.setString(1, srid);
        ResultSet rs = stmt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        for (int i = 0; i < len; i++) {
            rs.moveToInsertRow();
            JSONObject tr = trs.getJSONObject(i);
            for (int col = 1; col <= rsmd.getColumnCount(); col++) {
                String cn = rsmd.getColumnLabel(col);
                rs.updateObject(cn, tr.opt(cn));
            }
            rs.insertRow();
            rs.last();
            rs.updateRow();
        }
        LOG.debug("crs imported");
    }

    try (Connection conn = this.getConnection()) {
        String sql = "SELECT * FROM " + CaseResultMetric.TABLE_NAME + ";";
        PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
        stmt.setMaxRows(1);
        ResultSet rs = stmt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        for (int i = 0; i < len; i++) {
            JSONArray jarr = trs.getJSONObject(i).optJSONArray("CASE_result_metrics");
            if (jarr == null) {
                continue;
            }
            int l = jarr.length();
            for (int j = 0; j < l; j++) {
                JSONObject trm = jarr.getJSONObject(j);
                rs.moveToInsertRow();
                for (int col = 1; col <= rsmd.getColumnCount(); col++) {
                    String cn = rsmd.getColumnLabel(col);
                    if (cn.equals(CaseResultMetric.CASE_RESULT_METRIC_ID)) {
                        continue;
                    }
                    rs.updateObject(cn, trm.get(cn));
                }
                rs.insertRow();
                rs.last();
                rs.updateRow();
            }
        }
        LOG.debug("crms imported");
    }
}

From source file:com.nextep.designer.synch.services.impl.DataCaptureService.java

private IVersionable<IDataSet> fetchDataSet(Connection conn, DBVendor vendor, IBasicTable t,
        List<IBasicColumn> columns, IProgressMonitor m) throws SQLException {
    final String taskName = "Capturing " + t.getName() + " data";
    SubMonitor monitor = SubMonitor.convert(m, taskName, 100);
    monitor.subTask(taskName);//from w w  w .j ava2s  .c  o  m
    final IVersionable<IDataSet> v = VersionableFactory.createVersionable(IDataSet.class);
    final IDataSet dataSet = v.getVersionnedObject().getModel();
    final Collection<IDataLine> datalineBuffer = new ArrayList<IDataLine>(BUFFER_SIZE);
    // Configuring dataset
    dataSet.setTable(t);
    // Aligning captured data set with repository dataset name
    if (!t.getDataSets().isEmpty()) {
        // Taking first one
        final IDataSet set = t.getDataSets().iterator().next();
        // Captured data set will be named just like the repository dataset to force name synch
        dataSet.setName(set.getName());
        // Captured columns are restricted to defined data set columns only
        columns = set.getColumns();
    } else {
        dataSet.setName(t.getName());
    }
    for (IBasicColumn c : columns) {
        dataSet.addColumn(c);
    }
    // Fetching data
    Statement stmt = null;
    ResultSet rset = null;
    long counter = 0;
    try {
        stmt = conn.createStatement();
        final String dataSelect = buildDataSelect(vendor, t, columns);
        monitor.subTask(taskName + " - querying data");
        rset = stmt.executeQuery(dataSelect);
        final ResultSetMetaData md = rset.getMetaData();
        int bufferCount = 0;
        while (rset.next()) {
            // Handling cancellation
            if (monitor.isCanceled()) {
                return v;
            } else {
                if (counter++ % 100 == 0) {
                    monitor.worked(100);
                }
            }
            // Preparing dataline
            final IDataLine line = typedObjectFactory.create(IDataLine.class);

            // Iterating over result set columns
            for (int i = 1; i <= md.getColumnCount(); i++) {
                // Fetching result set column value
                Object value = null;
                try {
                    value = rset.getObject(i);
                } catch (SQLException e) {
                    LOGGER.error("Data import problem on " + t.getName() + " column " + i + " of line "
                            + counter + " failed to fetch data, NULL will be used instead [" + e.getMessage()
                            + "]", e); //$NON-NLS-1$
                }
                // Preparing column value
                final IColumnValue colValue = typedObjectFactory.create(IColumnValue.class);
                colValue.setDataLine(line);
                colValue.setColumn(columns.get(i - 1));
                colValue.setValue(value);
                line.addColumnValue(colValue);
            }
            datalineBuffer.add(line);
            if (++bufferCount >= BUFFER_SIZE) {
                dataService.addDataline(dataSet, datalineBuffer.toArray(new IDataLine[datalineBuffer.size()]));
                datalineBuffer.clear();
                bufferCount = 0;
                monitor.subTask(taskName + " - " + counter + " lines fetched"); //$NON-NLS-1$
            }
        }
        // Flushing end of buffer
        if (!datalineBuffer.isEmpty()) {
            dataService.addDataline(dataSet, datalineBuffer.toArray(new IDataLine[datalineBuffer.size()]));
        }
        LOGGER.info("Captured " + counter + " data lines from " + t.getName());
    } catch (SQLException e) {
        LOGGER.error("Unable to fetch data from table " + t.getName()
                + ": this table may need structure synchronization: " + e.getMessage(), e);
    } finally {
        if (rset != null) {
            rset.close();
        }
        if (stmt != null) {
            stmt.close();
        }
    }
    monitor.done();
    // Only returning dataset if at least one row was fetched
    return counter == 0 ? null : v;
}

From source file:com.hangum.tadpole.rdb.core.editors.table.TableViewerEditPart.java

/**
 * ??  .//from   w  w  w  .jav  a  2s.c o m
 * 
 * 1) ResultSetMetaData  ??  ? .
 * 
 * @param requestQuery
 * @param startResultPos
 * @param endResultPos
 */
private void runSQLSelect(String whereSQL) throws Exception {
    String requestQuery = "SELECT * FROM " + initTableNameStr; //$NON-NLS-1$
    if (!"".equals(whereSQL)) { //$NON-NLS-1$
        requestQuery += " where " + whereSQL; //$NON-NLS-1$
    }

    //  .
    //
    //
    //
    //
    //      if(DBDefine.MSSQL_DEFAULT != DBDefine.getDBDefine(userDB.getTypes())) {
    requestQuery = PartQueryUtil.makeSelect(userDB, requestQuery, 0, 500);
    //      } else {
    //         requestQuery = requestQuery + " top 500";
    //      }

    ResultSet rs = null;
    java.sql.Connection javaConn = null;

    try {
        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
        javaConn = client.getDataSource().getConnection();

        PreparedStatement stmt = null;
        stmt = javaConn.prepareStatement(requestQuery);

        rs = stmt.executeQuery();//Query( selText );

        // table column? 
        ResultSetMetaData rsm = rs.getMetaData();
        int columnCount = rsm.getColumnCount();
        for (int i = 0; i < rsm.getColumnCount(); i++) {
            //            if(logger.isDebugEnabled()) logger.debug(i + "[type]" + rsm.getColumnClassName(i+1) ); //$NON-NLS-1$
            tableDataTypeList.put(i, rsm.getColumnClassName(i + 1));
        }

        // rs set? ?? 
        tableDataList = new ArrayList<HashMap<Integer, Object>>();
        originalDataList = new ArrayList<HashMap<Integer, Object>>();
        HashMap<Integer, Object> tmpRs = null;

        mapColumns = SQLUtil.mataDataToMap(rs);

        while (rs.next()) {
            tmpRs = new HashMap<Integer, Object>();

            /** column modify info */
            tmpRs.put(0, TbUtils.COLUMN_MOD_TYPE.NONE.toString());

            for (int i = 1; i < columnCount + 1; i++) {
                try {
                    tmpRs.put(i, XMLUtils.xmlToString(rs.getString(i) == null ? "" : rs.getString(i)));
                } catch (Exception e) {
                    logger.error("ResutSet fetch error", e);
                    tmpRs.put(i, "");
                }
            }

            tableDataList.add(tmpRs);
            // ??  update where  .
            HashMap<Integer, Object> clondRs = (HashMap<Integer, Object>) tmpRs.clone();
            originalDataList.add(clondRs);
        }

    } finally {
        try {
            rs.close();
        } catch (Exception e) {
        }
        try {
            javaConn.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.termmed.statistics.Processor.java

/**
 * Prints the report.//w ww .  j  av a2 s  .c  o m
 *
 * @param bw the bw
 * @param detail the detail
 * @param listDescriptors 
 * @throws Exception the exception
 */
private void printReport(BufferedWriter bw, OutputDetailFile detail,
        List<HierarchicalConfiguration> listDescriptors) throws Exception {

    SQLStatementExecutor executor = new SQLStatementExecutor(connection);
    AdditionalList[] additionalList = null;
    if (listDescriptors != null) {
        additionalList = getAdditionalList(listDescriptors);
    }
    Integer ixSctIdInReport = detail.getSctIdIndex();
    if (ixSctIdInReport == null) {
        ixSctIdInReport = 1;
    }
    List<IReportListener> dependentReports = null;
    if (enableListeners) {
        ReportListeners reportListenersDescriptors = detail.getReportListeners();
        if (reportListenersDescriptors != null) {
            dependentReports = initListeners(reportListenersDescriptors, detail);
        }
    }
    for (StoredProcedure sProc : detail.getStoredProcedure()) {
        executor.executeStoredProcedure(sProc, ImportManager.params, null);
        ResultSet rs = executor.getResultSet();
        if (rs != null) {
            ResultSetMetaData meta = rs.getMetaData();
            String fieldValue;
            String sctId = "";
            String line;
            while (rs.next()) {
                line = "";
                for (int i = 0; i < meta.getColumnCount(); i++) {
                    if (rs.getObject(i + 1) != null) {
                        fieldValue = rs.getObject(i + 1).toString().replaceAll(",", "&#44;").trim();
                        if (ixSctIdInReport.intValue() == i) {
                            sctId = fieldValue;
                        }
                    } else {
                        fieldValue = "";
                        if (ixSctIdInReport.intValue() == i) {
                            sctId = "0";
                        }
                    }
                    line += fieldValue;
                    //                  bw.append(fieldValue);
                    if (i + 1 < meta.getColumnCount()) {
                        line += ",";
                        //                     bw.append(",");
                    } else {
                        if (additionalList != null && detail.getCreateInterestConceptList()) {
                            for (int ix = 0; i < additionalList.length; ix++) {

                                line += ",";
                                //                           bw.append(",");
                                if (additionalList[ix].getIds().contains(sctId)) {

                                    line += "1";
                                    //                              bw.append("1");
                                } else {
                                    line += "0";
                                    //                              bw.append("0");
                                }
                            }
                        }
                        bw.append(line);
                        bw.append("\r\n");
                        if (dependentReports != null) {
                            for (IReportListener dependentReport : dependentReports) {
                                dependentReport.actionPerform(line);
                            }
                        }
                    }
                }
            }
            meta = null;
            rs.close();
        }

    }
    executor = null;

    if (dependentReports != null) {
        for (IReportListener dependentReport : dependentReports) {
            dependentReport.finalizeListener();
        }
    }
}