jason
jason

Reputation: 259

How to get row count in groovy sql

Am new to groovy. Want to know how to get the number of rows from a given sql result returned form an sql query below. I have googled lot but didn't find the proper solution.

Here is my sql query class code

def sql = Sql.newInstance(dataSource);

    try
    {
        data = sql.rows("select field_value,form_table_column_name from 
               form_tbl where form_id=1");
        sql_one.close()

    } catch(Exception e) {

       System.out.println(e)      
    }

Upvotes: 10

Views: 22306

Answers (5)

Ansis Svaža
Ansis Svaža

Reputation: 87

sql.firstRow() is good to execute single-row SQL statements. Elvis operator helps if SQL result has no rows.

def cnt = SQL
     .firstRow('SELECT COUNT(*) AS cnt FROM form_tbl WHERE form_id=:id', id:1)
     ?.cnt

Upvotes: 3

test user
test user

Reputation: 1

keep in mind data.size() will still return 1, when using count(*) even if it returns 0, but the row count still=1

Upvotes: 0

Srinath Thota
Srinath Thota

Reputation: 1248

Here is the code to get the count of rows in grails. Firstly autowire the datasource in your service and create an Sql object from that as shown.This Sql should be imported from groovy.sql.Sql

Sql sql = new Sql(datasource)   

Then with the code below u can get the count as long.

def result = sql.firstRow('select count(*) as cont from <table>')
long count = result.cont

There is no need to fetch complete records from the database

Upvotes: 24

concrain
concrain

Reputation: 1

sql.each row(" SELECT COUNT(*) FROM db.table WHERE field= myField"){
    def total += it.count
}

Upvotes: -3

Joshua Moore
Joshua Moore

Reputation: 24776

To get the count or size of the records returned used data.size().

Upvotes: 10

Related Questions