Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle: cannot execute sql, driver not found

Tags:

gradle

I have got the following gradle script. It results in No suitable driver found error which I found strange.

buildscript {
    repositories{
        maven {
            url = 'http://localhost:8090/nexus/content/groups/public/'
        }
    }
    dependencies {
        classpath 'com.oracle:ojdbc6:11.2.0.4.0'
    }
}

task sql << {
    def url = 'jdbc:oracle:thin:@' + project.properties['db_hostname'] + ':' + project.properties['db_port'] + ':' + project.properties['db_sid']
    println 'sql, db url:' + url
    def driverName = 'oracle.jdbc.OracleDriver'
    Class.forName(driverName).newInstance();
    groovy.sql.Sql sql = groovy.sql.Sql.newInstance(
            url,
            project.properties['db_username'],
            project.properties['db_password'],
            driverName
    )
}

The error is:

Tasks to be executed: [task ':sql']
:sql (Thread[main,5,main]) started.
:sql
Executing task ':sql' (up-to-date check took 0.0 secs) due to:
  Task has not declared any outputs.
truncating, db url:jdbc:oracle:thin:@LOCALHOST:1521:orcl
:sql FAILED
:sql (Thread[main,5,main]) completed. Took 0.105 secs.

FAILURE: Build failed with an exception.

* Where:
Build file '/home/fran/projects/jua/build.gradle' line: 49

* What went wrong:
Execution failed for task ':sql'.
> No suitable driver found for jdbc:oracle:thin:@LOCALHOST:1521:orcl

* Try:
Run with --debug option to get more log output.
like image 307
user3111525 Avatar asked May 30 '26 06:05

user3111525


1 Answers

The driver jar is being loaded in a different classloader context than the Sql class. To fix it, try adding this:

// Add jars resolved by buildscript classpath configuration to the classloader which Sql will use 
URLClassLoader loader = groovy.sql.Sql.class.classLoader
project.buildscript.configurations.classpath.each { File file ->
  loader.addURL(file.toURL())
}

prior to the call to Sql.newInstance(). It will make all your classpath dependencies available to the Groovy classloader which loads the Sql class. The Class.forName() should not be neccesary.

See the discussion here for more information: http://gradle.1045684.n5.nabble.com/using-jdbc-driver-in-a-task-fails-td1435189.html

like image 88
Tom Tresansky Avatar answered Jun 02 '26 03:06

Tom Tresansky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!