get a data block by the sql sentence.

@param sqlqueryAllCount
@param sqlquery
@return if not found, return null;
17825
public Block getBlock(String sqlquery, Collection queryParams, int startIndex, int count) {
		Debug.logVerbose("[JdonFramework]enter getBlock .. ", module);
		if ((count > this.blockLength) || (count <= 0)) { // every query max
			// length must be
			// little than
			// blockLength
			count = this.blockLength;
		}
		QueryConditonDatakey qcdk = new QueryConditonDatakey(sqlquery, queryParams, startIndex, count, this.blockLength);
		Block block = getBlock(qcdk);
		if (block.getCount() > 0) {
			Debug.logVerbose("[JdonFramework]got a Block" + block.getCount(), module);
			return block;
		} else {
			Debug.logVerbose("[JdonFramework]not found the block!", module);
			return null;
		}
	}
294174
public ResultSet executeQuery(final String query) throws SQLException {
        startTimer();
        try {
            if (queryResult != null) {
                queryResult.close();
            }
            final Query queryToSend = queryFactory.createQuery(query);
            queryResult = protocol.executeQuery(queryToSend);
            warningsCleared = false;
            return new DrizzleResultSet(queryResult, this, getProtocol());
        } catch (QueryException e) {
            throw SQLExceptionMapper.get(e);
        } finally {
            stopTimer();
        }
    }
698454
public CountQueryResult executeCount() {
		CountQueryResult ret = new CountQueryResult(this);
		Object so = this.queryExecutor.getMappingInfo().getInternalDomainAccess().getSyncObject();
		if (so != null) {
			synchronized (so) {
				this.queryExecutor.executeCount();
			}
		} else
			this.queryExecutor.executeCount();
		return ret;
	}
376314
private Query getReportQueryByCriteriaCount(ReportQueryByCriteria aQuery)
    {
        ReportQueryByCriteria countQuery = (ReportQueryByCriteria) getQueryByCriteriaCount(aQuery);

        // BRJ: keep the original columns to build the Join
        countQuery.setJoinAttributes(aQuery.getAttributes());

        // BRJ: we have to preserve groupby information
        Iterator iter = aQuery.getGroupBy().iterator();
        while(iter.hasNext())
        {
            countQuery.addGroupBy((FieldHelper) iter.next());
        }

        return countQuery;
    }
1286643
private int getTotalCount(String sql, Connection conn, MappedStatement ms, BoundSql boundSql) throws SQLException {
    int start = sql.indexOf("from");
    if (start == -1) {
      throw new RuntimeException("statement has no 'from' keyword");
    }
    int stop = sql.indexOf("order by");
    if (stop == -1) {
      stop = sql.length();
    }

    String countSql = "select count(0) " + sql.substring(start, stop);
    BoundSql countBoundSql = new BoundSql(ms.getConfiguration(), countSql, boundSql.getParameterMappings(), boundSql.getParameterObject());
    ParameterHandler parameterHandler = new DefaultParameterHandler(ms, boundSql.getParameterObject(), countBoundSql);
    PreparedStatement stmt = null;
    ResultSet rs = null;
    int count = 0;
    try {
      stmt = conn.prepareStatement(countSql);
      // 通过parameterHandler给PreparedStatement对象设置参数
      parameterHandler.setParameters(stmt);
      rs = stmt.executeQuery();
      if (rs.next()) {
        count = rs.getInt(1);
      }
    } finally {
      CloseableUtil.closeQuietly(rs);
      CloseableUtil.closeQuietly(stmt);
    }
    return count;
  }
1305392
public List queryMultiObject(Collection queryParams, String sqlquery) throws Exception {
		Debug.logVerbose("[JdonFramework]--> enter queryMultiObject ", module);
		Connection c = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List list = new ArrayList();
		try {
			c = dataSource.getConnection();
			ps = c.prepareStatement(sqlquery, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
			Debug.logVerbose("[JdonFramework]" + sqlquery, module);
			jdbcUtil.setQueryParams(queryParams, ps);

			rs = ps.executeQuery();
			list = jdbcUtil.extract(rs);
		} catch (SQLException se) {
			throw new SQLException("SQLException: " + se.getMessage());
		} catch (Exception ex) {
			Debug.logError(ex, module);
			throw new Exception(ex);
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException quiet) {
				}
			if (ps != null)
				try {
					ps.close();
				} catch (SQLException quiet) {
				}
			if (c != null)
				try {
					c.close();
				} catch (SQLException quiet) {
				}
		}
		return list;
	}
866553
public int queryObjJoinCountByCondition(String sql){
		/*		JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
		.getDbSource(dbName);*/
		JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
		logger.debug(sql);
		Integer total=jdbcTemplate.queryForObject(sql,Integer.class);
		return total;
	}
705830
public long countQuery(SearchRequestBuilder countRequestBuilder,
            long timeoutMillis) {
        countRequestBuilder.setSize(0);
        return searchQuery("countQuery", countRequestBuilder, timeoutMillis)
                .getHits().getTotalHits();
    }
94858
public int count(Connection conn, Entity where) throws SQLException {
		checkConn(conn);
		
		final Query query = new Query(SqlUtil.buildConditions(where), where.getTableName());
		PreparedStatement ps = null;
		try {
			ps = dialect.psForCount(conn, query);
			return SqlExecutor.query(ps, new NumberHandler()).intValue();
		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(ps);
		}
	}
816585
private Status runQuery(QueryOptions options, QueryRowBlock block) {
        if (options == null)
            options = new QueryOptions();

        // OPT: It would be faster to use separate tables for raw-or ascii-collated views so that
        // they could be indexed with the right collation, instead of having to specify it here.
        String collationStr = "";
        if (collation == View.TDViewCollation.TDViewCollationASCII)
            collationStr += " COLLATE JSON_ASCII";
        else if (collation == View.TDViewCollation.TDViewCollationRaw)
            collationStr += " COLLATE JSON_RAW";


        StringBuilder sql = new StringBuilder("SELECT key, value, docid, revs.sequence");
        if (options.isIncludeDocs()) {
            sql.append(", revid, json");
        }
        sql.append(String.format(Locale.ENGLISH, " FROM 'maps_%s', revs, docs", mapTableName()));
        sql.append(" WHERE 1");

        List<String> argsList = new ArrayList<String>();

        if (options.getKeys() != null && options.getKeys().size() > 0) {
            sql.append(" AND key in (");
            String item = "?";
            for (Object key : options.getKeys()) {
                // null key should be ignored
                if (key != null) {
                    sql.append(item);
                    item = ", ?";
                    argsList.add(toJSONString(key));
                }
            }
            sql.append(')');
        }

        Object minKey = options.getStartKey();
        Object maxKey = options.getEndKey();
        String minKeyDocId = options.getStartKeyDocId();
        String maxKeyDocId = options.getEndKeyDocId();

        boolean inclusiveMin = options.isInclusiveStart();
        boolean inclusiveMax = options.isInclusiveEnd();
        if (options.isDescending()) {
            Object min = minKey;
            minKey = maxKey;
            maxKey = min;
            inclusiveMin = inclusiveMax;
            inclusiveMax = true;
            minKeyDocId = options.getEndKeyDocId();
            maxKeyDocId = options.getStartKeyDocId();
        }

        if (minKey != null) {
            String minKeyJSON = toJSONString(minKey);
            sql.append(inclusiveMin ? " AND key >= ?" : " AND key > ?");
            sql.append(collationStr);
            argsList.add(minKeyJSON);
            if (minKeyDocId != null && inclusiveMin) {
                //OPT: This calls the JSON collator a 2nd time unnecessarily.
                sql.append(String.format(Locale.ENGLISH, " AND (key > ? %s OR docid >= ?)", collationStr));
                argsList.add(minKeyJSON);
                argsList.add(minKeyDocId);
            }
        }

        if (maxKey != null) {
            maxKey = View.keyForPrefixMatch(maxKey, options.getPrefixMatchLevel());
            String maxKeyJSON = toJSONString(maxKey);
            sql.append(inclusiveMax ? " AND key <= ?" : " AND key < ?");
            sql.append(collationStr);
            argsList.add(maxKeyJSON);
            if (maxKeyDocId != null && inclusiveMax) {
                sql.append(String.format(Locale.ENGLISH, " AND (key < ? %s OR docid <= ?)", collationStr));
                argsList.add(maxKeyJSON);
                argsList.add(maxKeyDocId);
            }
        }

        sql.append(String.format(Locale.ENGLISH,
                " AND revs.sequence = 'maps_%s'.sequence AND docs.doc_id = revs.doc_id ORDER BY key",
                mapTableName()));
        sql.append(collationStr);
        if (options.isDescending()) {
            sql.append(" DESC");
        }
        sql.append(options.isDescending() ? ", docid DESC" : ", docid");

        sql.append(" LIMIT ? OFFSET ?");
        argsList.add(Integer.toString(options.getLimit()));
        argsList.add(Integer.toString(options.getSkip()));

        Log.v(Log.TAG_VIEW, "Query %s: %s | args: %s", name, sql.toString(), argsList);

        Status status = new Status(Status.OK);
        Cursor cursor = null;
        try {
            cursor = store.getStorageEngine().rawQuery(sql.toString(),
                    argsList.toArray(new String[argsList.size()]));
            // regular query
            cursor.moveToNext();
            while (!cursor.isAfterLast()) {
                // Call the block!
                byte[] keyData = cursor.getBlob(0);
                byte[] valueData = cursor.getBlob(1);
                String docID = cursor.getString(2);
                status = block.onRow(keyData, valueData, docID, cursor);
                if (status.isError())
                    break;
                else if (status.getCode() <= 0) {
                    status = new Status(Status.OK);
                    break;
                }
                cursor.moveToNext();
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return status;
    }
874029
public Long countByQueryFieldQueryRepliesInAndData(QueryField queryField, Collection<QueryReply> queryReplies, Double data) {
    if (queryReplies == null || queryReplies.isEmpty()) {
      return 0l;
    }
    
    EntityManager entityManager = getEntityManager();

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> criteria = criteriaBuilder.createQuery(Long.class);
    Root<QueryQuestionNumericAnswer> root = criteria.from(QueryQuestionNumericAnswer.class);
    Join<QueryQuestionNumericAnswer, QueryReply> replyJoin = root.join(QueryQuestionNumericAnswer_.queryReply);
    
    criteria.select(criteriaBuilder.count(root));
    criteria.where(
      criteriaBuilder.and(
        criteriaBuilder.equal(root.get(QueryQuestionNumericAnswer_.queryField), queryField),
        root.get(QueryQuestionNumericAnswer_.queryReply).in(queryReplies),
        criteriaBuilder.equal(root.get(QueryQuestionNumericAnswer_.data), data),
        criteriaBuilder.equal(replyJoin.get(QueryReply_.archived), Boolean.FALSE)
      )
    );
    
    return entityManager.createQuery(criteria).getSingleResult();
  }
731756
public String getStatement() throws SQLException {
		StringBuilder sb = new StringBuilder();
		appendSql(null, sb, new ArrayList<ArgumentHolder>());
		return sb.toString();
	}
1095663
private Connection getJdbcConnection() throws JspCoreException, SQLException {

        Connection conn = null;

        String url = getConnProperties().getUrl();
        String user = getConnProperties().getLoginUser();
        String passwd = getConnProperties().getLoginPasswd();
        String jndiName = getConnProperties().getJndiName();

        //System.out.println("***** Query.getJdbcConnection():  jndiname = " + jndiName);

        if (jndiName == null) { // use driver manager
            // load driver
            String dbDriver = (getConnProperties()).getDbDriver();
            try {
                Class.forName(dbDriver);
                conn = DriverManager.getConnection(url, user, passwd);
            } // try load driver
            catch (ClassNotFoundException e) {
                //com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.webcontainer.jsp.tsx.db.Query.getJdbcConnection", "174", this);
                throw new JspCoreException(JspConstants.InvalidDbDriver + dbDriver);
            } // catch
        } // if jndiname == null
        else { // use datasource
            DataSource ds;
            try {
                ds = getSingleton(jndiName);
            }
            catch (Throwable th) {
                //com.ibm.ws.ffdc.FFDCFilter.processException(th, "com.ibm.ws.webcontainer.jsp.tsx.db.Query.getJdbcConnection", "184", this);
                throw new JspCoreException(JspConstants.DatasourceException + th.getMessage());
            }
            conn = ds.getConnection(user, passwd);
        }

        return conn;
    }
1007160
final public static function limitFindBySql (string $sqlQuery, int $limit=0)
	{
		$resultArray = static::findBySql($sqlQuery.static::limitQuery($limit));
		if (empty($resultArray)) return FALSE;
		return ($limit == 1) ? array_shift($resultArray) : $resultArray;
	}
228792
public Object firstRow() throws SQLException {
        List rows = rows();
        if (rows.isEmpty()) return null;
        return (rows.get(0));
    }
1275674
public int count(Entity where) throws SQLException {
		Connection conn = null;
		try {
			conn = this.getConnection();
			return runner.count(conn, where);
		} catch (SQLException e) {
			throw e;
		} finally {
			this.closeConnection(conn);
		}
	}
569573
@NotNull
    public T queryNN() throws SQLException {
        T res = null;
        try (ResultSet r = statement.executeQuery()) {
            if (r.next()) {
                res = resultMapper.map(r);
            }
            Objects.requireNonNull(res);
            return res;
        }
    }