简体   繁体   English

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

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

I used to have a Java Class in my Grails app, but I needed to get a connection from DataSource.groovy so I passed it to a Groovy Class, and I made it getting the Context Application. 我曾经在Grails应用程序中有一个Java类,但是我需要从DataSource.groovy获得连接,所以我将其传递给了Groovy类,并获得了Context Application。 But How can I connect to that that Datasource with this code?: 但是如何使用此代码连接到该数据源?:

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

I need it like this because I need the Metadata of the result query like this: 我需要这样,因为我需要这样的结果查询的元数据:

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

and control it with a While: 并用While控制它:

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

I would use the groovy.sql package to do this. 我将使用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']
  ...
}

You can also access the ResultSetMetaData as well. 您也可以访问ResultSetMetaData This blog post has a good example of how to do so. 这篇博客文章提供了一个很好的例子。

you can also use auto-wiring in a service/controller: 您还可以在服务/控制器中使用自动接线:

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