Re: How to get result from SELECT count(*) FROM ...

From: Bryan Lewis (brya..aine.rr.com)
Date: Mon Nov 28 2005 - 09:27:20 EST

  • Next message: Gentry, Michael \(Contractor\): "RE: How to get result from SELECT count(*) FROM ..."

    noban asked:
    > How to get result from "SELECT count(*) FROM ... "?

    I'm appending the method I use. I got it from this thread:
    http://www.objectstyle.org/cayenne/lists/cayenne-user/2005/06/0106.html

    Andrus commented at the time, "1.2 will likely encapsulate this code in a
    generic utility class." I wonder if that's happened?

        /** A convenience method for executing a "SELECT COUNT(*)" sql
    statement.
         * Returns zero if the SQL statement gets a null result.
         */
        public static Integer getIntegerWithSql(DataContext dc, String sql)
        {
            DataMap queryRoot =
    dc.getEntityResolver().getDataMap("data_map_name");
            SQLTemplate query = new SQLTemplate(queryRoot, sql, true);
            query.setFetchingDataRows(true);

            Map singleRow = (Map) dc.performQuery(query).get(0);

            Integer value = null;
            if (singleRow != null) {
                Object obj = singleRow.values().iterator().next();
                if (obj instanceof Integer) {
                    value = (Integer) obj;
                }
                // Postgres returns a BigDecimal while Oracle returns Integer,
    so
                // check for Number.
                else if (obj instanceof Number) {
                    value = new Integer(((Number) obj).intValue());
                }
            }
            if (value == null) {
                value = new Integer(0);
            }
            return value;
        }



    This archive was generated by hypermail 2.0.0 : Mon Nov 28 2005 - 09:27:27 EST