Wednesday, October 29, 2008

Grails: How to query a database with SQL outside GORM and return an HTML SELECT

Here is an example of how to perform a query outside GORM and pass it to a view for display in a drop down select ...



import groovy.sql.Sql

class DbTableListController {

// The datasource for this grails app is injected
// automatically by it's name

def dataSource

def create = {
groovy.sql.Sql sql = new groovy.sql.Sql(dataSource)

def tableNames = []
sql.eachRow("""
SELECT
unique ( table_name )
FROM
ALL_TAB_COLUMNS
WHERE
OWNER = 'CRDEV'
""", { row ->
println "Found " << row.table_name
tableNames << row.table_name
}
)

def dbTableList = new DbTableList()
dbTableList.properties = params
return ['dbTableList':dbTableList, 'tableNames' : tableNames]
}

// Other Methods deleted ...
}



Then it's displayed in the create.gsp for this controller with this code:


< g:select id="tableName" name="tableName" from="${tableNames}" />

2 comments:

  1. The eachRow method of sql, passing in two arguments, the first being the query string, the second being a closure to print out some values.

    See: Here

    ReplyDelete