繁体   English   中英

如何使用此groovy代码从Groovy类获取DataSource连接?

[英]How to get DataSource connection from a Groovy Class with this groovy code?

我曾经在Grails应用程序中有一个Java类,但是我需要从DataSource.groovy获得连接,所以我将其传递给了Groovy类,并获得了Context Application。 但是如何使用此代码连接到该数据源?:

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()){..........}

我将使用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 这篇博客文章提供了一个很好的例子。

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

class SomeService {

 DataSource dataSource

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM