获取智能的countSql

@param sql
@param name 列名，默认 0
@return
481000
public String getSmartCountSql(String sql, String name) {
        //解析SQL
        Statement stmt = null;
        //特殊sql不需要去掉order by时，使用注释前缀
        if(sql.indexOf(KEEP_ORDERBY) >= 0){
            return getSimpleCountSql(sql);
        }
        try {
            stmt = CCJSqlParserUtil.parse(sql);
        } catch (Throwable e) {
            //无法解析的用一般方法返回count语句
            return getSimpleCountSql(sql);
        }
        Select select = (Select) stmt;
        SelectBody selectBody = select.getSelectBody();
        try {
            //处理body-去order by
            processSelectBody(selectBody);
        } catch (Exception e) {
            //当 sql 包含 group by 时，不去除 order by
            return getSimpleCountSql(sql);
        }
        //处理with-去order by
        processWithItemsList(select.getWithItemsList());
        //处理为count查询
        sqlToCount(select, name);
        String result = select.toString();
        return result;
    }
54422
public static String getCountSQL(String query) {
		if (query == null) {
			return null;
		}
		query = query.trim();
		if (StringUtils.startsWithIgnoreCase(query, "select")) {
			StringBuffer pagingSelect = new StringBuffer(query.length() + 30);
			pagingSelect.append("select count(*) from ( ");
			pagingSelect.append(query);
			pagingSelect.append(" ) t");
			return pagingSelect.toString();
		}
		return null;
	}
908905
public Query getCountQuery(Query aQuery)
    {
        if(aQuery instanceof QueryBySQL)
        {
            return getQueryBySqlCount((QueryBySQL) aQuery);
        }
        else if(aQuery instanceof ReportQueryByCriteria)
        {
            return getReportQueryByCriteriaCount((ReportQueryByCriteria) aQuery);
        }
        else
        {
            return getQueryByCriteriaCount((QueryByCriteria) aQuery);
        }
    }
122153
def get_count_sql(self):
        
        sql = 'SELECT COUNT(*) FROM ' + self.tables
        if len(self.where_clauses) > 0:
            sql += ' WHERE '
            sql += ' AND '.join(self.where_clauses)
        return sql
334863
async def count(query, clear_limit=False):
    
    clone = query.clone()
    if query._distinct or query._group_by or query._limit or query._offset:
        if clear_limit:
            clone._limit = clone._offset = None
        sql, params = clone.sql()
        wrapped = 'SELECT COUNT(1) FROM (%s) AS wrapped_select' % sql
        raw = query.model.raw(wrapped, *params)
        return (await scalar(raw)) or 0
    else:
        clone._returning = [peewee.fn.Count(peewee.SQL('*'))]
        clone._order_by = None
        return (await scalar(clone)) or 0
754299
def count_rows(self, table_name):
        """"""
        self.table_must_exist(table_name)
        query = "SELECT COUNT (*) FROM `%s`" % table_name.lower()
        self.own_cursor.execute(query)
        return int(self.own_cursor.fetchone()[0])
874960
@Override
    public SqlQuery createSqlQuery(String sql) {
        Assert.hasText(sql, "sql must has text");
        return ebeanServer.createSqlQuery(sql);
    }
1247081
public int getIndex(String name) throws SQLException {
    if (name == null) {
      throw new SQLException("Column name cannot be null");
    }
    String lowerName = name.toLowerCase(Locale.ROOT);
    // The specs in JDBC 4.0 specify that ResultSet.findColumn and
    // ResultSet.getXXX(String name) should use column alias (AS in the query). If label is not found, we use
    // original table name.
    if (aliasMap == null) {
      aliasMap = new HashMap<>();
      int counter = 0;
      for (ColumnInformation ci : columnInfo) {
        String columnAlias = ci.getName();
        if (columnAlias != null) {
          columnAlias = columnAlias.toLowerCase(Locale.ROOT);
          aliasMap.putIfAbsent(columnAlias, counter);

          String tableName = ci.getTable();
          if (tableName != null) {
            aliasMap.putIfAbsent(tableName.toLowerCase(Locale.ROOT) + "." + columnAlias, counter);
          }
        }
        counter++;
      }
    }

    Integer res = aliasMap.get(lowerName);
    if (res != null) {
      return res;
    }

    if (originalMap == null) {
      originalMap = new HashMap<>();
      int counter = 0;
      for (ColumnInformation ci : columnInfo) {
        String columnRealName = ci.getOriginalName();
        if (columnRealName != null) {
          columnRealName = columnRealName.toLowerCase(Locale.ROOT);
          originalMap.putIfAbsent(columnRealName, counter);

          String tableName = ci.getOriginalTable();
          if (tableName != null) {
            originalMap
                .putIfAbsent(tableName.toLowerCase(Locale.ROOT) + "." + columnRealName, counter);
          }
        }
        counter++;
      }
    }

    res = originalMap.get(lowerName);

    if (res == null) {
      throw ExceptionMapper.get("No such column: " + name, "42S22", 1054, null, false);
    }
    return res;

  }
492304
public PreparedStatementCreator count(final Dialect dialect) {
        return new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection con)
            throws SQLException {
                return getPreparedStatementCreator()
                .setSql(dialect.createCountSelect(builder.toString()))
                .createPreparedStatement(con);
            }
        };
    }
1172207
public long queryForCountStar(DatabaseConnection databaseConnection) throws SQLException {
		if (countStarQuery == null) {
			StringBuilder sb = new StringBuilder(64);
			sb.append("SELECT COUNT(*) FROM ");
			databaseType.appendEscapedEntityName(sb, tableInfo.getTableName());
			countStarQuery = sb.toString();
		}
		long count = databaseConnection.queryForLong(countStarQuery);
		logger.debug("query of '{}' returned {}", countStarQuery, count);
		return count;
	}
399689
public static int countChar(String s, char c) {

        int counter = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == c) {
                counter++;
            }
        }
        return counter;
    }
1124134
protected int count(UserCustomResultSet resultSet) {
		int count = 0;
		try {
			count = resultSet.getCount();
		} finally {
			resultSet.close();
		}
		return count;
	}
1149415
private String createCountSql(String sql) {
        StringBuilder sb = new StringBuilder("select count(0) from ( ");
        sb.append(sql).append(" ) as t");
        return sb.toString();
    }
544714
def count *where
    sql, *binds = SQLHelper.count :table => name, :where => @query_where + where, :prepared => true
    pstmt = prepare :count, sql
    pstmt.query(*binds).to_a[0][0].to_i
  end
475384
@Override
	public long count(final String col) {
		final String expr = col != null
				? tableMetadata.getColumn(CaseFormat.CAMEL_CASE.convert(col)).getColumnIdentifier()
				: "*";
		StringBuilder sql = new StringBuilder("select count(").append(expr).append(") from (")
				.append(System.lineSeparator())
				.append(aggregationSourceSql())
				.append(System.lineSeparator())
				.append(") t_");
		context().setSql(sql.toString());
		try (ResultSet rs = agent().query(context())) {
			rs.next();
			return rs.getLong(1);
		} catch (final SQLException e) {
			throw new EntitySqlRuntimeException(SqlKind.SELECT, e);
		}
	}
1318426
public int queryObjCountByCondition(String tableName, String condition,Object[] paramArray){
		/*		JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
		.getDbSource(dbName);*/
		//String tableName=changeTableNameCase(otableName);
		JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
		String sql="";
		sql="select count(1) from " + tableName + " where "+condition;
		logger.debug(sql);
		logger.debug(Arrays.toString(paramArray));
		Integer total=jdbcTemplate.queryForObject(sql,Integer.class,paramArray);
		return total;
	}
1019360
def get_number_of_rows(dbcon, tablename, uuid=None):
    
    dbcur = dbcon.cursor()
    if check_table_exists(dbcon, tablename):
        if uuid:
            dbcur.execute("SELECT COUNT(*) FROM '{name}' WHERE UUID='{uuid}'".format(name=tablename, uuid=uuid))
        else:
            dbcur.execute("SELECT COUNT(*) FROM '{name}'".format(name=tablename))
        try:
            result = dbcur.fetchone()[0]
        except (TypeError, IndexError) as e:
            logger.error(e)
            result = 0
        dbcur.close()
        return result if isinstance(result, (int, long, float)) else 0
    else:
        return 0