prayagupadhyay
prayagupadhyay

Reputation: 31252

grails - print each row's value with column name from GroovyRowResult

I want to let a user fire sql query and then see the result in grails view page.

My QueryController.groovy is

def query(){
    def headers = null; //["id","name"]
    Sql sql = new Sql(dataSource)
    def rowResults = sql.rows(params.query) //GroovyRowResult
    rowResults.eachWithIndex { row, index->
           if (headers == null) {
                   headers = row.keySet()
           }
    }
    [headers : headers, resultList: rowResults, total : rowResults.size() ]

}

In grails view page (query.gsp),

<table class="table table-striped">
           <thead>
               <tr>
                  <g:each in="${headers}" var="header">
                     <g:sortableColumn property="header" title="${header}" />
                     <th></th>
                  </g:each>
              </tr>
            </thead>
            <tbody>
                <g:each in="${resultList}" var="row">
                   <tr>
                      <g:each status="counter" in="${row}" var="val">
                           <td>${val}</td>
                      </g:each>
                   </tr>
                </g:each>

             </tbody>
         </table>

The <td>${val}</td> part in view is not working as expected, because it gives result as id=1 instead of 1. I want only value to be displayed there.

Might be a smaller issue though, need to fix it.

Thanks.

Upvotes: 1

Views: 5550

Answers (2)

Alidad
Alidad

Reputation: 5538

Try accessing values by accessing the value on each map:

<table class="table table-striped" border="1">
    <thead>
    <tr>
        <g:each in="${headers}" var="header">
            <g:sortableColumn property="header" title="${header}" />
        </g:each>
    </tr>

    </thead>
    <tbody>
    <g:each in="${resultList}" var="row">
        <tr>
            <g:each status="counter" in="${row}" var="val">
                <td>${val.value}</td>
            </g:each>
        </tr>
    </g:each>

    </tbody>
</table>

/

Also in your query action you can get the header directly from the map:

 def query(){
        def headers = null; //["id","name"]
        Sql sql = new Sql(dataSource)
        def rowResults = sql.rows("select * from Message;") //GroovyRowResult

       // rowResults is a list, you can access it by its index
        headers = rowResults[0].keySet()  

FYI, what you are giving your users is very powerful and they can run any sort of query against you database even to drop your tables.

Upvotes: 3

prayagupadhyay
prayagupadhyay

Reputation: 31252

Well, I got the following code working as val is KVP.

<tr>
                      <g:each status="counter" in="${row}" var="val">
                           <td>${val.value}</td>
                      </g:each>
</tr>

Upvotes: 0

Related Questions