Skip to content

Counting rows

Counting records in a table is easy.


DATABASE ExampleDatabase
PACKAGE com.example.db
SERVER ExampleServer
SCHEMA ToDoList_App

TABLE ToDoList
   ID               SEQUENCE
   ListName         CHAR(255)
   ListType         SHORT (Private=1, Public=2)
   Description      CHAR(255)
   LastUpdated      TIMESTAMP

KEY PKEY PRIMARY
    ID

PROC Count

Count

Counts the number of records in a table.

Count

Count will count the number of records in a table.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@dataclass
class DB_ToDoListCount:
    #Outputs
    noOf: int

    @classmethod
    def get_statement(cls
                     ) -> TextAsFrom:
        class _ret:
            sequence = "default," #postgres uses default for sequences
            output = " OUTPUT (noOf)"
            tail = " RETURNING noOf"
            #session.bind.dialect.name

        statement = sa.text(
                        f"/* PROC ToDoList_App.ToDoList.Count */"
                        f"select count(*) noOf from ToDoList_App.ToDoList")

        text_statement = statement.columns(noOf=sa.types.Integer,
                                      )
        return text_statement

    @classmethod
    def execute(cls, session: Session) -> Optional['DB_ToDoListCount']:
        res = session.execute(cls.get_statement())
        rec = res.fetchone()
        if rec:
            res.close()
            return process_result_rec(DB_ToDoListCount, session, [sa.types.Integer,
                                        ], rec)

        return None
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
  public boolean count() throws SQLException
  {
    String statement = 
      "/* PROC BooksAndAuthors.ToDoList.Count */"
    + "select count(*) noOf from BooksAndAuthors.ToDoList"
    ;
    PreparedStatement prep = connector.prepareStatement(statement);
    ResultSet result = prep.executeQuery();
    if (!result.next())
    {
      result.close();
      prep.close();
      return false;
    }
    noOf =  result.getInt(1);
    result.close();
    prep.close();
    return true;
  }