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:com.p5solutions.core.jpa.orm.rowbinder.EntityRowBinder.java

/**
 * Gets the basic result object./*from  ww w.  ja va  2s .co m*/
 * 
 * @param rs
 *          the rs
 * @return the basic result object
 * @throws SQLException
 *           the sQL exception
 */
private Object getBasicResultObject(ResultSet rs) throws SQLException {
    final boolean isPlainClass = Object.class.equals(entityClass);
    final boolean isBasicClass = ReflectionUtility.isBasicClass(entityClass);

    ResultSetMetaData metaData = rs.getMetaData();

    // if the entity is a of sub-type object.class or is some sort of
    // primitive class such as BigDecimal, Integer, Double, Short, etc.
    if (isPlainClass || isBasicClass) {

        // / obviously if we have more than one column, we cannot
        // possibly map it
        // / to a plain old java object of type Object.class, since
        // there are no
        // / members to map the columns to!
        if (metaData.getColumnCount() > 1) {
            String error = "Cannot return multi-column resultset into "
                    + "a plain object of type Object.class. If you need to map a multi-column "
                    + "resultset, please use an object marked with @" + Entity.class + " annotation.";
            logger.error(error);

            throw new RuntimeException(error);
        }

        // // THIS SHOULD NEVER HAPPEN, QUERY EXCEPTION SHOULD
        // // BE THROWN IF THERE IS A SYNTAX ERROR IN THE QUERY.
        // if (metaData.getColumnCount() == 0) { }

        // Otherwise if there is only 1 column, and its within the scope
        // of plain object.class
        return (T) rs.getObject(1);
    }

    return null;
}

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

/**
 * /*from   www .j  a  va  2s  .  c om*/
 */
public void processNullKingdom() {
    PrintWriter pw = null;
    try {
        pw = new PrintWriter("gbif_plants_from_null.log");

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

    System.out.println("----------------------- Searching NULL ----------------------- ");

    String gbifWhereStr = "FROM raw WHERE kingdom IS NULL";

    long startTime = System.currentTimeMillis();

    String cntGBIFSQL = "SELECT COUNT(*) " + gbifWhereStr;// + " LIMIT 0,1000";
    String gbifSQL = gbifSQLBase + gbifWhereStr;

    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 {
        pw = new PrintWriter("gbif_plants_from_null.log");

        pStmt = dstConn.prepareStatement(pSQL);

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

        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:i5.las2peer.services.loadStoreGraphService.LoadStoreGraphService.java

/**
 * //  w  w w  . j  a  va 2 s .  co 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:net.antidot.semantic.rdf.rdb2rdf.r2rml.core.R2RMLEngine.java

private Map<ColumnIdentifier, byte[]> applyValueToRow(TermMap tm) throws SQLException {
    Map<ColumnIdentifier, byte[]> result = new HashMap<ColumnIdentifier, byte[]>();
    Set<ColumnIdentifier> columns = tm.getReferencedColumns();
    for (ColumnIdentifier column : columns) {
        log.debug("[R2RMLEngine:applyValueToRow] Iterate over : " + column);

        int i;//from  w ww  . j a va2  s.c o m
        final ResultSetMetaData metaData = rows.getMetaData();
        int n = metaData.getColumnCount();
        boolean found = false;
        for (i = 1; i <= n; i++) {
            ColumnIdentifier cId = ColumnIdentifierImpl.buildFromJDBCResultSet(metaData, i);
            log.debug("[R2RMLEngine:applyValueToRow] Test column : " + cId);
            if (cId.equals(column)) {
                log.debug("[R2RMLEngine:applyValueToRow] Value found : \"" + rows.getString(i) + "\" (Type: "
                        + cId.getSqlType() + ")");
                byte[] rawData = rows.getBytes(i);

                // http://bugs.mysql.com/bug.php?id=65943
                if (rawData != null && R2RMLProcessor.getDriverType().equals(DriverType.MysqlDriver)
                        && cId.getSqlType() == SQLType.CHAR) {
                    rawData = rows.getString(i).getBytes();
                }
                result.put(cId, rawData);
                found = true;
                break;
            }
        }
        if (!found)
            // Second chance fails...
            throw new SQLException("[R2RMLEngine:applyValueToRow] Unknown column : " + column);
    }
    return result;
}

From source file:in.sc.dao.ProductHelper.java

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

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

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

/**
 * ??  ./* ww  w . j a v  a2 s .com*/
 * 
 * 1) ResultSetMetaData  ??  ? .
 * 
 * @param strWhere
 * @param strOrderBy
 */
private void runSQLSelect(String strWhere, String strOrderBy) throws Exception {
    String requestQuery = "SELECT "; //$NON-NLS-1$

    if (userDB.getDBDefine() == DBDefine.ORACLE_DEFAULT) {
        requestQuery += " rowid, "; //$NON-NLS-1$
    } else if (userDB.getDBDefine() == DBDefine.POSTGRE_DEFAULT) {
        requestQuery += " ctid, "; //$NON-NLS-1$
    }
    List<TableColumnDAO> tmpTableColumns = TadpoleObjectQuery.getTableColumns(userDB, tableDao);
    for (int i = 0; i < tmpTableColumns.size(); i++) {
        TableColumnDAO tabledao = tmpTableColumns.get(i);
        requestQuery += tabledao.getName();
        if (i < (tmpTableColumns.size() - 1))
            requestQuery += ","; //$NON-NLS-1$
    }

    requestQuery += " FROM " + SQLUtil.getTableName(userDB, tableDao);

    if (!"".equals(strWhere)) //$NON-NLS-1$
        requestQuery += " where " + strWhere; //$NON-NLS-1$
    if (!"".equals(strOrderBy)) //$NON-NLS-1$
        requestQuery += " order by " + strOrderBy; //$NON-NLS-1$
    if (logger.isDebugEnabled())
        logger.debug("Last query is " + requestQuery);

    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);
        stmt.setMaxRows(GetPreferenceGeneral.getSelectLimitCount());

        rs = stmt.executeQuery();

        // 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<Map<Integer, Object>>();
        originalDataList = new ArrayList<Map<Integer, Object>>();
        HashMap<Integer, Object> tmpRs = null;

        mapColumns = ResultSetUtils.getColumnName(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 {
                    String strValue = rs.getString(i) == null ? "" : rs.getString(i);
                    //                  System.out.println("ogiginal: "+ strValue);
                    //                  strValue = StringEscapeUtils.unescapeHtml(strValue);
                    //                  System.out.println("unescapeHtml: "+ strValue);
                    //                  strValue = StringEscapeUtils.unescapeXml(strValue);
                    //                  System.out.println("unescapeXml: "+ strValue);
                    strValue = StringEscapeUtils.escapeXml(strValue);

                    tmpRs.put(i, strValue); //$NON-NLS-1$
                } catch (Exception e) {
                    logger.error("ResutSet fetch error", e); //$NON-NLS-1$
                    tmpRs.put(i, ""); //$NON-NLS-1$
                }
            }

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

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

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

public LinkedHashMap<String, Field> resultSetToFields(ResultSet rs, int maxClobSize, int maxBlobSize,
        Map<String, DataType> columnsToTypes, ErrorRecordHandler errorRecordHandler,
        UnknownTypeAction unknownTypeAction, Set<String> recordHeader, boolean timestampToString)
        throws SQLException, StageException {
    ResultSetMetaData md = rs.getMetaData();
    LinkedHashMap<String, Field> fields = new LinkedHashMap<>(md.getColumnCount());

    for (int i = 1; i <= md.getColumnCount(); i++) {
        try {/*from ww  w  . ja v  a2  s  .  c  o m*/
            if (recordHeader == null || !recordHeader.contains(md.getColumnName(i))) {
                DataType dataType = columnsToTypes.get(md.getColumnName(i));
                Field field = resultToField(md, rs, i, maxClobSize, maxBlobSize,
                        dataType == null ? DataType.USE_COLUMN_TYPE : dataType, unknownTypeAction,
                        timestampToString);
                fields.put(md.getColumnLabel(i), field);
            }
        } catch (SQLException e) {
            errorRecordHandler.onError(JdbcErrors.JDBC_13, e.getMessage(), e);
        } catch (IOException e) {
            errorRecordHandler.onError(JdbcErrors.JDBC_03, md.getColumnName(i), rs.getObject(i), e);
        }
    }

    return fields;
}

From source file:com.viettel.ttbankplus.servicegw.hibernate.dao.transaction.TransCPDAO.java

public List<Transaction> getTrans(String where, HashMap param) {
    List lst = new ArrayList();
    try {//from   w  ww . j a v a  2s.  c o m

        String sql = "select cp.trans_id transId, cp.content_provider_id contentproviderid,  to_char(cp.request_date, 'dd/MM/yyyy hh24:mi:ss') requestDate, "
                + "(case nvl(bp.error_code,'null')\n" + "when '00' then TO_CHAR(2)\n" + "when '32' then \n"
                + "(case nvl(bp.correct_code,'null')\n" + "when '00' then TO_CHAR(2)\n"
                + "when 'null' then TO_CHAR(1)\n" + "else TO_CHAR(4) end)\n" + "when 'null' then\n"
                + "(case nvl(bp.correct_code,'null')\n" + "when '00' then TO_CHAR(2)\n"
                + "when 'null' then TO_CHAR(1)\n" + "else TO_CHAR(4) end\n" + ")\n" + "when 'null' then\n"
                + "(case nvl(bp.correct_code,'null')\n" + "when '00' then TO_CHAR(2)\n"
                + "when 'null' then TO_CHAR(1)\n" + "else TO_CHAR(4) end\n" + ")\n" + "else TO_CHAR(4)\n"
                + "end\n" + ")" + " transStatus, "
                + "cp.confirm_status confirmStatus, cp.billing_code billingCode, cp.order_id orderId, cp.amount, "
                + "cp.order_info orderInfo, cp.trans_type transType, bp.bank_code bankCode, bp.cp_code cpCode, bp.msisdn, p.cp_name cpName, bp.customer_name customerName, bp.error_code || bp.correct_code errorCode from trans_cp cp join trans_bankplus bp on cp.trans_cp_id = bp.trans_cp_id "
                + " join content_provider p on p.content_provider_id = cp.content_provider_id ";
        //            sql += where;
        //            sql += " order by cp.request_date desc";
        //            log.debug(sql);
        //Rebuild where param
        int numparam = StringUtils.countMatches(where, ":");
        //            log.info("NUM PARAM: " + numparam);
        ArrayList<Object> arrParam = new ArrayList<Object>();
        arrParam.add(0, "");
        for (int i = 0; i < numparam; i++) {
            for (Object object : param.keySet()) {
                String key = object.toString();
                Object val = param.get(key);
                int index = where.indexOf(":");
                int indexCheck = where.indexOf(":" + key);
                if (index == indexCheck) {
                    if (val instanceof ArrayList) {
                        ArrayList arr = (ArrayList) val;
                        String add = "";
                        for (int j = 0; j < arr.size(); j++) {
                            arrParam.add(arr.get(j));
                            add += ",?";
                        }
                        add = add.substring(1);
                        where = where.substring(0, index) + add + where.substring(index + (":" + key).length());
                    } else if (val instanceof Date) {
                        Date d = (Date) val;
                        String date = new SimpleDateFormat("dd/MM/yyyy HH-mm-ss").format(d);
                        arrParam.add(date);
                        where = where.substring(0, index) + "to_date(?,'dd/MM/yyyy hh24-mi-ss')"
                                + where.substring(index + (":" + key).length());
                    } else {
                        arrParam.add(val);
                        where = where.substring(0, index) + "?" + where.substring(index + (":" + key).length());
                    }
                    //                        arrParam.add(val);
                    //                        where = where.substring(0, index) + "?" + where.substring(index + (":" + key).length());
                    break;
                }
            }
        }
        numparam = arrParam.size() - 1;
        sql += where;
        sql += " order by cp.request_date desc";
        //            log.debug(sql);
        log.info("WHERE CLAUSE: " + where);
        log.info("LIST PARAM VALUE: " + arrParam);

        Session sess = DAOFactory.getNewSession();
        //            SQLQuery query = sess.createSQLQuery(sql);

        Connection conn = sess.connection();

        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            pstm = conn.prepareStatement(sql);
            for (int i = 0; i < numparam; i++) {
                Object objVal = arrParam.get(i + 1);
                if (objVal instanceof ArrayList) {
                    ArrayList arrlist = (ArrayList) objVal;
                    java.sql.Array sqlArray = null;
                    //                        oracle.jdbc.OracleConnection oracleConnection = conn.unwrap(OracleConnection.class);
                    if (arrlist.get(0) instanceof String) {

                        //                            sqlArray = oracleConnection.createArrayOf("VARCHAR", arrlist.toArray());
                        //                            sqlArray = conn.createArrayOf("VARCHAR", arrlist.toArray());
                    } else {
                        //                            sqlArray = conn.createArrayOf("NUMERIC", arrlist.toArray());
                        //                            sqlArray = oracleConnection.createArrayOf("INTEGER", arrlist.toArray());
                    }
                    pstm.setArray(i + 1, sqlArray);
                } else if (objVal instanceof String) {
                    pstm.setString(i + 1, objVal.toString());
                    //                        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
                    //                        log.info("set string: " + (i + 1) + " - " + objVal.toString());
                } else if (objVal instanceof Date) {
                    Date d = (Date) objVal;
                    //                        String date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d);
                    java.sql.Timestamp sqlDate = new java.sql.Timestamp(d.getTime());
                    //                        log.info("set date: " + (i + 1) + " - " + sqlDate);
                    pstm.setTimestamp(i + 1, sqlDate);
                    //                        pstm.setString(i + 1, date);
                } else {
                    pstm.setLong(i + 1, Long.parseLong(objVal.toString()));
                    //                        log.info("set long: " + (i + 1) + " - " + Long.parseLong(objVal.toString()));
                }
            }
            //                log.info("PREP: " + pstm.toString());
            rs = pstm.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int numCol = rsmd.getColumnCount();
            String[] arrCol = new String[numCol];
            String coltemp = "";
            for (int i = 0; i < numCol; i++) {
                arrCol[i] = rsmd.getColumnName(i + 1);
                coltemp += rsmd.getColumnName(i + 1) + "#";
            }
            //                log.info("CCCCCC:" + coltemp);
            while (rs.next()) {
                //                    log.info("AAAAAAAAAAAAA:" + rs.getString(1));
                Transaction trans = new Transaction();
                for (int i = 0; i < numCol; i++) {
                    //                        String data = rs.getString(arrCol[i]);
                    Object data = rs.getObject(arrCol[i]);
                    if (data != null) {
                        callSetFunction(trans, "set" + arrCol[i], data);
                    }
                }
                lst.add(trans);
            }

        } catch (Exception ex) {
            log.error("", ex);
        } finally {
            //                log.info("================>finally");
            if (rs != null) {
                rs.close();
            }
            if (pstm != null) {
                pstm.close();
            }

            if (sess != null) {
                sess.close();
            }
        }
        //            query.setResultTransformer(Transformers.aliasToBean(Transaction.class));
        //            for (Object object : param.keySet()) {
        //                String key = object.toString();
        //                Object val = param.get(key);
        //                if (val instanceof ArrayList) { //For select in
        //                    query.setParameterList(key, (ArrayList) val);
        //                } else {
        //                    query.setParameter(key, param.get(key));
        //                }
        //            }
        //            log.info(query.toString());
        //            lst = query.list();
        //            ScrollableResults resultset = query.scroll(ScrollMode.FORWARD_ONLY);
        //            resultset.beforeFirst();
        //            while (resultset.next()) {
        //                Object[] objres = resultset.get();
        //                log.info(objres);
        //            }
        //            resultset.close();
    } catch (Exception ex) {
        log.error("getTrans: ", ex);
    } finally {
        //            DAOFactory.commitCurrentSessions();
    }

    return lst;
}

From source file:DatabaseServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    String sql = "select * from atable";
    Connection conn = null;//from w w w.  j  a v  a 2s.  c  o  m
    Statement stmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsm = null;

    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html><head><title>Typical Database Access</title></head><body>");
    out.println("<h2>Database info</h2>");
    out.println("<table border='1'><tr>");

    try {

        //load the database driver
        Class.forName("oracle.jdbc.driver.OracleDriver");

        //The JDBC URL for this Oracle database
        String url = "jdbc:oracle:thin:@142.3.169.178:1521:ORCL";

        //Create the java.sql.Connection to the database
        conn = DriverManager.getConnection(url, "usr", "pass");

        //Create a statement for executing some SQL
        stmt = conn.createStatement();

        rs = stmt.executeQuery(sql);

        rsm = rs.getMetaData();

        int colCount = rsm.getColumnCount();

        //print column names
        for (int i = 1; i <= colCount; ++i) {

            out.println("<th>" + rsm.getColumnName(i) + "</th>");
        }

        out.println("</tr>");

        while (rs.next()) {

            out.println("<tr>");

            for (int i = 1; i <= colCount; ++i)
                out.println("<td>" + rs.getString(i) + "</td>");

            out.println("</tr>");

        }

    } catch (Exception e) {

        throw new ServletException(e.getMessage());

    } finally {

        try {

            stmt.close();
            conn.close();

        } catch (SQLException sqle) {
        }

    }

    out.println("</table><br><br>");

    out.println("</body>");
    out.println("</html>");

    out.close();

}

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 w ww . ja v a2  s  .  c  o m*/
            } 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;
}