【问题标题】:How to get DataSource connection from a Groovy Class with this groovy code?如何使用这个 groovy 代码从 Groovy 类获取 DataSource 连接?
【发布时间】:2014-04-25 17:18:48
【问题描述】:

我曾经在我的 Grails 应用程序中有一个 Java 类,但我需要从 DataSource.groovy 获得一个连接,所以我将它传递给了一个 Groovy 类,然后我让它获得了上下文应用程序。但是我怎样才能用这段代码连接到那个数据源呢?:

def dataSource = ctx.getBean('dataSource_Executer') // auto injected and referenced to a datasource
Connection conn = null;
Statement stmt = null;
Class.forName('driver');
conn = DriverManager.getConnection(dataSource);// Here it's the trouble

我需要这样,因为我需要这样的结果查询的元数据:

 stmt = conn.createStatement();
 def rs = stmt.executeQuery('query');
 def rsmd = rs.getMetaData();
 num = rsmd.getColumnCount();

并用 While 控制它:

 while(rs.next()){..........}

【问题讨论】:

标签: java grails groovy datasource


【解决方案1】:

我会使用groovy.sql 包来执行此操作。

import groovy.sql.GroovyRowResult
import groovy.sql.Sql

def dataSource = ctx.getBean('dataSource_Executer')
def connection = new Sql(dataSource)
def results = connection.rows('SELECT ...')
results.each { r ->
  println r['columnName']
  ...
}

您也可以访问ResultSetMetaData。这个blog post 有一个很好的例子来说明如何做到这一点。

【讨论】:

    【解决方案2】:

    您还可以在服务/控制器中使用自动连接:

    class SomeService {
    
     DataSource dataSource
    
     @Transactional
     def someMethod( params = [:] ){
       Sql db = new Sql( dataSource )
       db.eachRow( "select * from table" ) {
         doSometething it
       }
       db.close()
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多