简体   繁体   中英

Groovy Sql to get the max value from a column

I have the following Groovy code to return the max value from the 'id' column from the 'topic' table:

 def rs = sql.executeQuery("select max(id) from topic")

 def maxId = rs.getLong(1)

It doesn't work, I get the following error:

java.sql.SQLException: Invalid column index at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:113) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:147) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:209)...

Does any one know what the correct code is? Thanks.

I think it would be easier if you'd use the method firstRow . You can either get the value from the result object by name or by index.

by name:

def row = sql.firstRow("select max(id) as max from topic")
def maxId = row.max

by index:

def row = sql.firstRow("select max(id) from topic")
def maxId = row[0]

Nobody seems to have mentioned that the index in rs.getLong(1) is out of bounds. Getting fields uses a starting index of 0. Binding fields uses a starting index of 1. Why? Historical SQL behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM