grails框架直接使用sql语句

    Grails自带了一些查询方法,或者使用hsql语句来进行查询,但是有些时候我们需要执行原生态的sql语句查询,不管该查询是否能进行,执行原生态的sql语句还是有它的好处的,不过具体情况 也得分分情况 。

    有人建议在程序里面直接创建一个数据库连接,然后执行查询,其实可以直接使用默认的数据源:

        需要导入包:

import groovy.sql.Sql
import org.codehaus.groovy.grails.commons.ApplicationHolder
import org.springframework.context.ApplicationContext

        查询代码:

      ApplicationContext ctx = (ApplicationContext) ApplicationHolder.getApplication().getMainContext();
      def dataSource = ctx.getBean('dataSource');
      def sql = new Sql(dataSource);
      String strSql = "select count( a.controll_plane_id) , palne_time from (select id, palne_time,controll_plane_id FROM  plane_time  where true group by palne_time, controll_plane_id,palne_time_status) a group by palne_time";

      sql.eachRow(strSql) {
  println it
      }
这样就能直接输出结果了.
[count( a.controll_plane_id):2, palne_time:2011-08-01]
[count( a.controll_plane_id):2, palne_time:2011-08-02]
[count( a.controll_plane_id):2, palne_time:2011-08-03]
[count( a.controll_plane_id):4, palne_time:2011-08-04]
[count( a.controll_plane_id):1, palne_time:2011-08-05]
[count( a.controll_plane_id):1, palne_time:2011-08-06]
[count( a.controll_plane_id):1, palne_time:2011-08-12]
[count( a.controll_plane_id):1, palne_time:2011-08-18]

你可能感兴趣的:(grails)