[groovy-user] Groovy Sql and table metadata

327 views
Skip to first unread message

Dean Del Ponte

unread,
Jan 26, 2012, 4:55:31 PM1/26/12
to us...@groovy.codehaus.org
How do I get metadata (ie. column names) from an empty table using Groovy Sql?

All of the examples I've found show how to do it for a table which contains data.

Thanks!

Dean Del Ponte

Dinko Srkoc

unread,
Jan 26, 2012, 7:39:25 PM1/26/12
to us...@groovy.codehaus.org
On 26 January 2012 22:55, Dean Del Ponte <dean.d...@gmail.com> wrote:
> How do I get metadata (ie. column names) from an empty table using Groovy
> Sql?
>
> All of the examples I've found show how to do it for a table which contains
> data.

It doesn't matter whether there is data or not, since you are after
metadata. If you look closer at the API you may notice some `eachRow`
and `rows` methods having `Closure metaClosure` among their
parameters. That closure is called once, even for empty tables, with
the `ResultSetMetaData` as argument.

def colNames
sql.rows('select * from empty_table') { meta ->
colNames = (1..meta.columnCount).collect {
meta.getColumnName(it)
}
}

Another way is to go strait to `DatabaseMetaData` and read columns from there:

def meta = sql.connection.metaData,
cols = meta.getColumns('a_catalog', null, 'empty_table', null)
def colNames = []
while (cols.next()) colNames << cols.getString('column_name')

(Note: be careful here about closing your connection)

Cheers,
Dinko

>
> Thanks!
>
> Dean Del Ponte

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email


Reply all
Reply to author
Forward
0 new messages