JDBC Programmers: How do I use SQL functions like count(*), max(*), etc.?

[Note: I am looking for definite factual info here, but the topic doesn’t seem to be of general enough interest to warrant placement in GQ].

When using SQL statements in a JDBC program, you create a statement object and then a ResultSet object that links your statement object with the query you want to execute. For example, the following code fragment will display the value of column FOO for every row in the BAR table:

**

Connection c = DriverManager.getConnection…(creates a db session)

Statement s = c.createStatement();
ResultSet r = s.executeQuery (“select FOO from BAR”);

while (r.next()){
System.out.println (r.getString(“foo”));
}**

But how do I code a statement that uses a builtin function like COUNT() or MAX()? Suppose I wanted to execute the query

**
select COUNT(*) from BAR where FOO=‘SOMEVALUE’"**, and save the result in an int variable?

I’ve poked around a bit but haven’t been able to figure this out. Any help would be appreciated.

You’re existing code should work; you just need to convert the returned data into an int using something like Integer.parseInt(s) where s is the returned column.

**
Connection c = DriverManager.getConnection();

Statement s = c.createStatement();
ResultSet r = s.executeQuery (“select count(*) as cn from BAR”);

while (r.next()){
System.out.println (r.getInt(“cn”));
}
**

Alternatively:
**
Connection c = DriverManager.getConnection();

Statement s = c.createStatement();
ResultSet r = s.executeQuery (“select count(*) from BAR”);

while (r.next()){
System.out.println (r.getInt(1));
}
**