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()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.