我有以下gradle
脚本。它导致No suitable driver found
错误,我觉得很奇怪。
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
)
}
错误是:
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.
答案 0 :(得分:3)
驱动程序jar正在加载到与Sql类不同的类加载器上下文中。要解决此问题,请尝试添加以下内容:
// 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())
}
在致电Sql.newInstance()
之前。它将使所有类路径依赖项可用于加载Sql
类的Groovy类加载器。 Class.forName()
不应该是必要的。
有关详细信息,请参阅此处的讨论: http://gradle.1045684.n5.nabble.com/using-jdbc-driver-in-a-task-fails-td1435189.html
答案 1 :(得分:0)
对我来说不起作用(Gradle 2.12)。
但不是表演:
Class.forName("org.h2.Driver")
我做了:
groovy.sql.loadDriver("org.h2.Driver")
Groovy Sql.loadDriver
方法做了一些漂亮的类加载器。
答案 2 :(得分:0)
你应该使用这样的东西:
configurations {
db2database
}
buildscript {
dependencies {
classpath('com.ibm.db2:db2jcc4:10.5.5')//db2 driver for gradle task
}
}
dependencies {
db2database "com.ibm.db2:db2jcc4:10.5.5" //db2 driver for configuration
}
//load drivers for gradle tasks
configurations.db2database.each {
GroovyObject.class.classLoader.addURL(it.toURI().toURL())
}
....
Sql sql = Sql.newInstance(
envProps.getProperty('dbUri'),
envProps.getProperty('dbUsername'),
envProps.getProperty('dbPassword'),
envProps.getProperty('dbDriverClassName')
)
println sql.rows("SELECT * FROM TEST.TEST")