phaseless wrote:
I'm trying to do some Sql stuff and added
import groovy.sql.Sql
but when I try to use the Sql class with a line like the following in a
gradle task
sql =
Sql.newInstance("jdbc:oracle:thin:@srv:1521:database","usr","pswrd","oracle.jdbc.OracleDriver")
I get a 'Class Not Found Exception'.
To resolve the drive dependencies I added the following lines at the
beginning of the build.gradle script:
buildscript {
repositories {
flatDir name: 'localRepository', dirs: 'lib'
}
dependencies {
classpath name: 'ojdbc14'
}
}
and put the oracle driver 'ojdbc14.jar' into the directory '$rootDir/lib'
which seems to be correctly resolved.
Even with these lines the driver class is not found.
Also other attempts to advice the DriverManager to register the oracle
driver like
Class.forName("oracle.jdbc.OracleDriver")
do not work, although the driver can be instanciated like this:
def oracleDriver = new oracle.jdbc.OracleDriver()
println "hello jdbc: " + oracleDriver.toString()
java.sql.DriverManager.registerDriver ( oracleDriver )
Registration seems not to be successful, since
java.sql.DriverManager.getDrivers().each { println "Driver: " + it.name }
does not respond anything.
I think, that there is a problem with the classLoader but can't figure out,
what!
Can anybody help?
DriverManager will only let you access drivers which have been loaded by
the calling class' classloader. In the build script, the caller to
DriverManager isn't actually the build script, it is Groovy. So, you
need to load the driver in the same classloader as Groovy.
Here is an example. It uses H2, but should work with the Oracle driver too.
configurations {
driver
}
dependencies {
driver "com.h2database:h2:1.2.120"
}
URLClassLoader loader = GroovyObject.class.classLoader
configurations.driver.each {File file ->
loader.addURL(file.toURL())
}
Class driver = loader.loadClass('org.h2.Driver')
// You might need one or both of these as well
// Driver instance = driver.newInstance()
// DriverManager.registerDriver(instance)
Sql sql = Sql.newInstance("jdbc:h2:$buildDir/test", "sa", "")
--
Adam Murdoch
Gradle Developer
http://www.gradle.org