Example usage for java.sql PreparedStatement setMaxRows

List of usage examples for java.sql PreparedStatement setMaxRows

Introduction

In this page you can find the example usage for java.sql PreparedStatement setMaxRows.

Prototype

void setMaxRows(int max) throws SQLException;

Source Link

Document

Sets the limit for the maximum number of rows that any ResultSet object generated by this Statement object can contain to the given number.

Usage

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

/**
 * ??  ./*from   w  w w  . j  a v  a  2s . c o  m*/
 * 
 * 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.dsf.dbxtract.cdc.journal.JournalExecutor.java

/**
 * Gets reference data from journal table.
 * //from  w w  w  .java  2  s . c  o  m
 * @param client
 * @param conn
 * @return a Map list with column names and values
 * @throws SQLException
 * @throws ConfigurationException
 */
private List<Map<String, Object>> getJournalKeys(CuratorFramework client, Connection conn)
        throws SQLException, ConfigurationException {

    List<Map<String, Object>> result = new ArrayList<>();
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        // Obtem os dados do journal
        if (logger.isDebugEnabled())
            logger.debug(logPrefix + "getting journalized data");
        StringBuilder baseQuery = new StringBuilder("select * from ").append(handler.getJournalTable());
        if (JournalStrategy.WINDOW.equals(handler.getStrategy())) {
            Long lastWindowId = getLastWindowId(client);
            baseQuery.append(" where window_id > ?");
            ps = conn.prepareStatement(baseQuery.toString());
            ps.setLong(1, lastWindowId);
        } else {
            ps = conn.prepareStatement(baseQuery.toString());
        }
        ps.setFetchSize(handler.getBatchSize());
        ps.setMaxRows(handler.getBatchSize());
        rs = ps.executeQuery();
        copyResultsetToMap(rs, result);

    } finally {
        DBUtils.close(rs);
        DBUtils.close(ps);
    }
    return result;
}

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

public List<Map<String, Object>> getSuitesResult(String project, long startTime, long stopTime,
        int numberOfEntries, String suiteName, String jobName, boolean invisibleIncluded)
        throws NamingException, SQLException {
    String sql = "SELECT * FROM " + SuiteResult.TABLE_NAME + " WHERE (" + SuiteResult.START_TIME + " > ?)"
            + " AND (" + SuiteResult.STOP_TIME + " < ?)";
    if (StringUtils.isNotBlank(suiteName)) {
        sql += " AND (" + SuiteResult.SUITE_NAME + " = ?)";
    } else if (StringUtils.isNotBlank(jobName)) {
        sql += " AND (" + SuiteResult.JOB_NAME + " = ?)";
    }//  w  w w .ja  va 2  s. c om
    if (StringUtils.isNotBlank(project)) {
        sql += " AND (" + SuiteResult.PROJECT_NAME + " LIKE ?)";
    }
    if (!invisibleIncluded) {
        sql += " AND NOT " + SuiteResult.INVISIBLE_ENTRY;
    }
    sql += " ORDER BY " + SuiteResult.START_TIME + " DESC;";
    try (Connection conn = this.getConnection()) {
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setLong(1, startTime);
        stmt.setLong(2, stopTime);
        if (StringUtils.isNotBlank(suiteName)) {
            stmt.setString(3, suiteName);
        } else if (StringUtils.isNotBlank(jobName)) {
            stmt.setString(3, jobName);
        }
        if (StringUtils.isNotBlank(project)) {
            if (StringUtils.isNotBlank(suiteName) || StringUtils.isNotBlank(jobName)) {
                stmt.setString(4, project + "%");
            } else {
                stmt.setString(3, project + "%");
            }
        }
        LOG.trace("{}", stmt);
        stmt.setMaxRows(numberOfEntries);
        ResultSet rs = stmt.executeQuery();
        return this.dumpResultSetToList(rs);
    }
}

From source file:com.taobao.tddl.jdbc.group.TGroupPreparedStatement.java

private PreparedStatement createPreparedStatementInternal(Connection conn, String sql) throws SQLException {
    PreparedStatement ps;
    if (autoGeneratedKeys != -1) {
        ps = conn.prepareStatement(sql, autoGeneratedKeys);
    } else if (columnIndexes != null) {
        ps = conn.prepareStatement(sql, columnIndexes);
    } else if (columnNames != null) {
        ps = conn.prepareStatement(sql, columnNames);
    } else {/*www . j a v a 2  s. co m*/
        int resultSetHoldability = this.resultSetHoldability;
        if (resultSetHoldability == -1) //setResultSetHoldability
            resultSetHoldability = conn.getHoldability();

        ps = conn.prepareStatement(sql, this.resultSetType, this.resultSetConcurrency, resultSetHoldability);
    }
    setBaseStatement(ps);
    ps.setQueryTimeout(queryTimeout); //setBaseStatement
    ps.setFetchSize(fetchSize);
    ps.setMaxRows(maxRows);

    return ps;
}

From source file:it.unibas.spicy.persistence.relational.DAORelational.java

private void getInstanceByTable(IConnectionFactory dataSourceDB, Connection connection, String schemaName,
        String tableName, INode setTable, IDataSourceProxy dataSource, boolean translated) throws DAOException {
    PreparedStatement statement = null;
    ResultSet resultSet = null;//from w w  w  .j a v a2s.  c  o m
    try {
        String tablePath = tableName;
        //mysql jdbc driver
        if (connection.getMetaData().getDriverName().equalsIgnoreCase(SpicyEngineConstants.MYSQL_DRIVER_NAME)) {
            tablePath = connection.getCatalog() + "." + tableName;
        } else if (!schemaName.equals("")) {
            tablePath = schemaName + ".\"" + tableName + "\"";
        }
        statement = connection.prepareStatement("select * from " + tablePath + " order by 1");
        statement.setMaxRows(NUMBER_OF_SAMPLE);
        resultSet = statement.executeQuery();
        if (resultSet == null) {
            throw new DAOException("ResultSet is NULL!");
        }
        int sampleCounter = 0;
        while (resultSet.next() && sampleCounter < NUMBER_OF_SAMPLE) {
            sampleCounter++;
            TupleNode tupleNode = new TupleNode(getNode(tableName + TUPLE_SUFFIX).getLabel(), getOID());
            setTable.addChild(tupleNode);
            for (INode attributeNodeSchema : getNode(tableName + TUPLE_SUFFIX).getChildren()) {
                AttributeNode attributeNode = new AttributeNode(attributeNodeSchema.getLabel(), getOID());
                String columnName = attributeNodeSchema.getLabel();
                String oldName = dataSource.getChangedValue(tableName + "." + columnName);
                if (oldName != null && !translated) {
                    columnName = oldName;
                }
                Object columnValue = resultSet.getObject(columnName);
                LeafNode leafNode = createLeafNode(attributeNodeSchema, columnValue);
                attributeNode.addChild(leafNode);
                tupleNode.addChild(attributeNode);
            }
        }
    } catch (SQLException sqle) {
        throw new DAOException(sqle.getMessage());
    } finally {
        dataSourceDB.close(resultSet);
        dataSourceDB.close(statement);
    }
}

From source file:com.alfaariss.oa.util.saml2.storage.artifact.jdbc.JDBCArtifactMapFactory.java

private void verifyTableConfig() throws OAException {
    Connection oConnection = null;
    PreparedStatement pVerify = null;
    try {/*from w  ww .j  a va2  s. c o m*/
        try {
            oConnection = _oDataSource.getConnection();
        } catch (SQLException e) {
            _logger.error("Could not connect to resource", e);
            throw new DatabaseException(SystemErrors.ERROR_INIT, e);
        }

        StringBuffer sb = new StringBuffer("SELECT ");
        sb.append(_sColumnID).append(", ");
        sb.append(_sColumnISSUER).append(", ");
        sb.append(_sColumnRELYING_PARTY).append(", ");
        sb.append(_sColumnMESSAGE).append(", ");
        sb.append(_sColumnEXPIRATION);
        sb.append(" FROM ");
        sb.append(_sTableName);
        //DD LIMIT 1 is not supported by derby, setMaxRows(1) is       

        pVerify = oConnection.prepareStatement(sb.toString());
        pVerify.setMaxRows(1);
        try {
            pVerify.executeQuery();
        } catch (Exception e) {
            StringBuffer sbError = new StringBuffer("Invalid table configured '");
            sbError.append(_sTableName);
            sbError.append("' verified with query: ");
            sbError.append(sb.toString());
            _logger.error(sbError.toString());
            throw new DatabaseException(SystemErrors.ERROR_INIT);
        }
    } catch (OAException e) {
        throw e;
    } catch (SQLException e) {
        _logger.error("SQL error during verification of configured table: " + e.getErrorCode(), e);
        throw new OAException(SystemErrors.ERROR_INIT, e);
    } catch (Exception e) {
        _logger.error("Internal error during verification of configured table", e);
        throw new OAException(SystemErrors.ERROR_INIT, e);
    } finally {
        try {
            if (pVerify != null)
                pVerify.close();
        } catch (SQLException e) {
            _logger.debug("Could not close statement", e);
        }
        try {
            if (oConnection != null)
                oConnection.close();
        } catch (SQLException e) {
            _logger.debug("Could not close connection", e);
        }
    }
}

From source file:com.octo.captcha.engine.bufferedengine.buffer.DatabaseCaptchaBuffer.java

/**
 * Remove a precise number of captcha with a locale
 *
 * @param number The number of captchas to remove
 * @param locale The locale of the removed captchas
 *
 * @return a collection of captchas//from   ww  w. j a  va 2 s .  c om
 */
public Collection removeCaptcha(int number, Locale locale) {
    Connection con = null;
    PreparedStatement ps = null;
    PreparedStatement psdel = null;
    ResultSet rs = null;
    Collection collection = new UnboundedFifoBuffer();
    Collection temp = new UnboundedFifoBuffer();
    if (number < 1) {
        return collection;
    }
    try {
        if (log.isDebugEnabled()) {
            log.debug("try to remove " + number + " captchas");
        }
        ;
        con = datasource.getConnection();

        ps = con.prepareStatement(
                "select *  from " + table + " where " + localeColumn + " = ? order by " + timeMillisColumn);

        psdel = con.prepareStatement(
                "delete from " + table + " where " + timeMillisColumn + "= ? and " + hashCodeColumn + "= ? ");//and " + localeColumn
        //+ "= ?");
        ps.setString(1, locale.toString());
        ps.setMaxRows(number);
        //read
        rs = ps.executeQuery();
        int i = 0;
        while (rs.next() && i < number) {
            try {
                i++;
                InputStream in = rs.getBinaryStream(captchaColumn);
                ObjectInputStream objstr = new ObjectInputStream(in);
                Object captcha = objstr.readObject();
                temp.add(captcha);
                //and delete
                long time = rs.getLong(timeMillisColumn);
                long hash = rs.getLong(hashCodeColumn);
                psdel.setLong(1, time);
                psdel.setLong(2, hash);
                //psdel.setString(3, rs.getString(localeColumn));
                psdel.addBatch();

                if (log.isDebugEnabled()) {
                    log.debug("remove captcha added to batch : " + time + ";" + hash);
                }

            } catch (IOException e) {
                log.error("error during captcha deserialization, "
                        + "check your class versions. removing row from database", e);
                psdel.execute();
            } catch (ClassNotFoundException e) {
                log.error("Serialized captcha class in database is not in your classpath!", e);
            }

        }
        //execute batch delete
        psdel.executeBatch();
        log.debug("batch executed");
        rs.close();
        //commit the whole stuff
        con.commit();
        log.debug("batch commited");
        //only add after commit
        collection.addAll(temp);
    } catch (SQLException e) {
        log.error(DB_ERROR, e);
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
            }
        }

    } finally {

        if (ps != null) {
            try {
                ps.close();
            } // rollback on error
            catch (SQLException e) {
            }
        }
        if (con != null) {
            try {
                con.close();
            } // rollback on error
            catch (SQLException e) {
            }
        }
    }
    return collection;
}

From source file:com.manydesigns.portofino.actions.admin.appwizard.ApplicationWizard.java

protected void detectLargeResultSet(Table table, CrudConfiguration configuration) {
    Boolean lrs = largeResultSet.get(table);
    if (lrs != null) {
        configuration.setLargeResultSet(lrs);
        return;//from  w w  w .  ja  v a 2 s.c om
    }

    Connection connection = null;
    try {
        logger.info("Trying to detect whether table {} has many records...", table.getQualifiedName());
        connection = connectionProvider.acquireConnection();
        liquibase.database.Database implementation = DatabaseFactory.getInstance()
                .findCorrectDatabaseImplementation(new JdbcConnection(connection));
        String sql = "select count(*) from "
                + implementation.escapeTableName(table.getSchemaName(), table.getTableName());
        PreparedStatement statement = connection.prepareStatement(sql);
        setQueryTimeout(statement, 1);
        statement.setMaxRows(1);
        ResultSet rs = statement.executeQuery();
        if (rs.next()) {
            Long count = safeGetLong(rs, 1);
            if (count != null) {
                if (count > LARGE_RESULT_SET_THRESHOLD) {
                    logger.info("Table " + table.getQualifiedName() + " currently has " + count
                            + " rows, which is bigger than " + "the threshold (" + LARGE_RESULT_SET_THRESHOLD
                            + ") for large result sets. It will be "
                            + "marked as largeResultSet = true and no autodetection based on table data will be "
                            + "attempted, in order to keep the processing time reasonable.");
                    configuration.setLargeResultSet(true);
                } else {
                    logger.info("Table " + table.getQualifiedName() + " currently has " + count
                            + " rows, which is smaller than " + "the threshold (" + LARGE_RESULT_SET_THRESHOLD
                            + ") for large result sets. It will be " + "analyzed normally.");
                }
            } else {
                logger.warn("Could not determine number of records, assuming large result set");
                configuration.setLargeResultSet(true);
            }
        }
        statement.close();
    } catch (Exception e) {
        logger.error("Could not determine count", e);
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            logger.error("Could not close connection", e);
        }
    }
    largeResultSet.put(table, configuration.isLargeResultSet());
}

From source file:com.manydesigns.portofino.actions.admin.appwizard.ApplicationWizard.java

protected void detectBooleanColumn(Table table, Column column) {
    if (detectedBooleanColumns.contains(column)) {
        return;//from  ww w  . j av  a 2  s.co m
    }

    if (column.getJdbcType() == Types.INTEGER || column.getJdbcType() == Types.DECIMAL
            || column.getJdbcType() == Types.NUMERIC) {
        logger.info("Detecting whether numeric column " + column.getQualifiedName()
                + " is boolean by examining " + "its values...");

        // Detect booleans
        Connection connection = null;

        try {
            connection = connectionProvider.acquireConnection();
            liquibase.database.Database implementation = DatabaseFactory.getInstance()
                    .findCorrectDatabaseImplementation(new JdbcConnection(connection));
            String sql = "select count(" + implementation.escapeDatabaseObject(column.getColumnName()) + ") "
                    + "from " + implementation.escapeTableName(table.getSchemaName(), table.getTableName());
            PreparedStatement statement = connection.prepareStatement(sql);
            setQueryTimeout(statement, 1);
            statement.setMaxRows(1);
            ResultSet rs = statement.executeQuery();
            Long count = null;
            if (rs.next()) {
                count = safeGetLong(rs, 1);
            }

            if (count == null || count < 10) {
                logger.info("Cannot determine if numeric column {} is boolean, count is {}",
                        column.getQualifiedName(), count);
                return;
            }

            sql = "select distinct(" + implementation.escapeDatabaseObject(column.getColumnName()) + ") "
                    + "from " + implementation.escapeTableName(table.getSchemaName(), table.getTableName());
            statement = connection.prepareStatement(sql);
            setQueryTimeout(statement, 1);
            statement.setMaxRows(3);
            rs = statement.executeQuery();
            int valueCount = 0;
            boolean only0and1 = true;
            while (rs.next()) {
                valueCount++;
                if (valueCount > 2) {
                    only0and1 = false;
                    break;
                }
                Long value = safeGetLong(rs, 1);
                only0and1 &= value != null && (value == 0 || value == 1);
            }
            if (only0and1 && valueCount == 2) {
                logger.info("Column appears to be of boolean type.");
                column.setJavaType(Boolean.class.getName());
            } else {
                logger.info("Column appears not to be of boolean type.");
            }
            statement.close();
        } catch (Exception e) {
            logger.debug("Could not determine whether column " + column.getQualifiedName() + " is boolean", e);
            logger.info("Could not determine whether column " + column.getQualifiedName() + " is boolean");
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                logger.error("Could not close connection", e);
            }
        }
        detectedBooleanColumns.add(column);
    }
}

From source file:net.xqx.controller.web.QyzzController.java

/**
 * ?/* w  w  w .jav  a2  s  . co  m*/
 * 
 * @return
 */
@RequestMapping("/fdckfqy")
public String fdckfqy(HttpServletRequest request) {
    PageDao pageDao = new PageDao();
    String pageCount = request.getParameter("pageCount");// ???
    if (pageCount == null || "".equals(pageCount)) {
        pageCount = "1";
    }
    int totalRow = 0;// ?
    String total = request.getParameter("totalRow");
    int totalrow = 0;
    if (null != total && !"".equals(total)) {
        totalrow = Integer.parseInt(total);
    }

    Page page = null;
    String companyName = request.getParameter("companyName");
    if (companyName != null && !"".equals(companyName)) {
        companyName = companyName.trim();
    }
    String certificateLevel = request.getParameter("certificateLevel");
    request.setAttribute("companyName", companyName);
    request.setAttribute("certificateLevel", certificateLevel);

    Connection conn = pageDao.getAptitudeConnection();
    PreparedStatement statement = null;
    ResultSet rs = null;
    String hql = "";
    try {

        if (companyName != null && !"".equals(companyName)
                && (certificateLevel == null || "".equals(certificateLevel))) {
            hql = "select count(*) from TCompanyInfo c left join TCertificate cer "
                    + "on c.fCompanyId=cer.fCompanyId left join TRegInfo r "
                    + "on c.fCompanyId=r.fCompanyInfoId where c.fChecked=1 and c.fCompanyName like " + "'" + "%"
                    + companyName + "%" + "'";
            String sql = "select c.fCompanyName,c.fCompanyType,c.fRightMan,r.fCapital,r.fPaiclUpCapital,r.fRegLicenseNo,"
                    + "cer.fCertificateLevel,cer.fCertificateNo,c.fOperatingDate,cer.fCertifyDate,"
                    + "cer.fValidBeginDate,cer.fValidEndDate,c.fAddress,c.fDetails,c.fCompanyId from TCompanyInfo c left join TCertificate cer "
                    + "on c.fCompanyId=cer.fCompanyId left join TRegInfo r "
                    + "on c.fCompanyId=r.fCompanyInfoId where c.fChecked=1 and c.fCompanyName like ? order by c.fCompanyId desc";
            totalRow = pageDao.getAmount(hql);// select count ?
            if (totalRow != totalrow) {
                pageCount = "1";
            }
            page = new Page(totalRow, pageCount, 11);
            statement = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            statement.setMaxRows(page.getEndIndex());
            statement.setString(1, "%" + companyName + "%");
            rs = statement.executeQuery();
            rs.first();
            rs.relative(page.getBeginIndex() - 1);
            request.setAttribute("totalPage", page.getTotal());// ?
            request.setAttribute("pageCount", page.getCount());// ??
            request.setAttribute("companyName", companyName);// ??
        } else if (companyName != null && !"".equals(companyName) && certificateLevel != null
                && !"".equals(certificateLevel)) {
            hql = "select count(*) from TCompanyInfo c left join TCertificate cer "
                    + "on c.fCompanyId=cer.fCompanyId left join TRegInfo r "
                    + "on c.fCompanyId=r.fCompanyInfoId where c.fChecked=1 and c.fCompanyName like " + "'" + "%"
                    + companyName + "%" + "'" + " and cer.fCertificateLevel=" + "'" + certificateLevel + "'";

            String sql = "select c.fCompanyName,c.fCompanyType,c.fRightMan,r.fCapital,r.fPaiclUpCapital,r.fRegLicenseNo,"
                    + "cer.fCertificateLevel,cer.fCertificateNo,c.fOperatingDate,cer.fCertifyDate,"
                    + "cer.fValidBeginDate,cer.fValidEndDate,c.fAddress,c.fDetails,c.fCompanyId from TCompanyInfo c left join TCertificate cer "
                    + "on c.fCompanyId=cer.fCompanyId left join TRegInfo r "
                    + "on c.fCompanyId=r.fCompanyInfoId where c.fChecked=1 and c.fCompanyName like ? and cer.fCertificateLevel=? order by c.fCompanyId desc";
            totalRow = pageDao.getAmount(hql);// select count ?
            if (totalRow != totalrow) {
                pageCount = "1";
            }
            page = new Page(totalRow, pageCount, 11);
            statement = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            statement.setMaxRows(page.getEndIndex());
            statement.setString(1, "%" + companyName + "%");
            statement.setString(2, certificateLevel);
            rs = statement.executeQuery();
            rs.first();
            rs.relative(page.getBeginIndex() - 1);
            request.setAttribute("totalPage", page.getTotal());// ?
            request.setAttribute("pageCount", page.getCount());// ??
            request.setAttribute("companyName", companyName);// ??
            request.setAttribute("certificateLevel", certificateLevel);// ??
        }

        TCompanyInfo companyInfo = null;
        List<TCompanyInfo> companyInfos = new ArrayList<TCompanyInfo>();
        if (rs != null) {
            while (rs.next()) {
                companyInfo = new TCompanyInfo();
                companyInfo.setfCompanyName(rs.getString(1));
                companyInfo.setfCompanyType(rs.getString(2));
                companyInfo.setfRightMan(rs.getString(3));
                companyInfo.setfCapitals(rs.getString(4));
                companyInfo.setfCapitalsUp(rs.getString(5));
                companyInfo.setfLicenseNo(rs.getString(6));
                companyInfo.setfCertificateLevel(rs.getString(7));
                companyInfo.setfCertificateNo(rs.getString(8));
                companyInfo.setfOperatingDate(rs.getString(9));
                companyInfo.setfCertificateDate(rs.getString(10));
                companyInfo.setfCertificateBeginDate(rs.getString(11));
                companyInfo.setfCertificateEndDate(rs.getString(12));
                companyInfo.setfRegAddress(rs.getString(13));
                companyInfo.setfDetails(rs.getString(14));
                companyInfo.setfCompanyId(rs.getInt(15));
                companyInfos.add(companyInfo);
            }
        }
        request.setAttribute("companyInfos", companyInfos);
        // rs.close();
        // statement.close();
        // conn.close();

    } catch (SQLException e) {
        System.out.println("!");
        e.printStackTrace();
        return "web/qycx";
    } finally {
        pageDao.closeConnection(rs, statement, conn);

    }

    // 
    Sort hotNewsSort = new Sort(Direction.DESC, "fdjTimes", "ffbTime");
    Pageable hotNewsRecPageable = new PageRequest(0, 8, hotNewsSort);
    List<TNews> hotNewsList = newsDao.getHotNews(hotNewsRecPageable).getContent();
    request.setAttribute("hotNewsList", hotNewsList);

    // ??
    Sort recNewsSort = new Sort(Direction.DESC, "fIsRecord", "ffbTime");
    Pageable recNewsRecPageable = new PageRequest(0, 8, recNewsSort);
    List<TNews> recNewsList = newsDao.getNewsRec(recNewsRecPageable).getContent();
    request.setAttribute("recNewsList", recNewsList);
    request.setAttribute("totalRow", totalRow);
    return "web/qycx";
}