質問

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. 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(rs.next()){..........}
役に立ちましたか?

解決

I would use the groovy.sql package to do this.

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. 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帰属
所属していません StackOverflow
scroll top