2012-03-13 123 views
2

我有一個jar依賴build.gradle文件本身。我使用這樣的定義:gradle build.gradle依賴 - oracle驅動程序?

buildscript { 
    repositories { 
     flatDir { 
      dirs 'lib' 
     } 
    } 
    dependencies { 
     classpath name: 'ojdbc16' 
    } 
} 

這個任務:

task mytask() << { 
    String updateQuery = "somequery" 
    println "Setting up test user with query:\n${updateQuery}" 
    Sql sql = Sql.newInstance("jdbc:oracle:thin:@//host:port/sid", user, password, 'oracle.jdbc.driver.OracleDriver') 
    boolean successful = sql.execute(updateQuery) 
} 

但我得到這個異常:

Caused by: org.codehaus.groovy.runtime.InvokerInvocationException: java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver 
    at org.gradle.api.internal.AbstractTask$ClosureTaskAction.execute(AbstractTask.java:452) 
    at org.gradle.api.internal.AbstractTask$ClosureTaskAction.execute(AbstractTask.java:436) 
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:60) 
    ... 54 more 
Caused by: java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver 
    at build_5kgfd83hhriam4rhlh34a1l160$_run_closure3.doCall(/Users/localadmin/projects/test-case-runner/build.gradle:41) 
    ... 57 more 

什麼可怎麼回事呢?我沒有得到有關類路徑定義的任何錯誤,所以我假設我的依賴關係解析工作正常。什麼可能會失敗?

+0

胡亂猜測的工作,但我注意到你的依賴被命名爲「ojdbc16」,有你改名爲罐子?原來的名字是'ojdbc6' – rlovtang 2012-03-14 18:15:28

+0

您是否嘗試過'classpath':ojdbc16:''而不是?我相信你的JAR文件沒有一個定義的版本號,用破折號分隔它的文件名嗎? – 2012-03-14 19:24:52

+0

如果你閱讀下面我更新的答案,語法是好的:P。 – 2012-03-14 20:39:49

回答

3
repositories { 
    flatDir name: 'localRepository', dirs: 'lib' 
} 

configurations { 
    driver 
} 

task mytask() << { 
    URLClassLoader loader = GroovyObject.class.classLoader 
    configurations.driver.each {File file -> 
     loader.addURL(file.toURL()) 
    } 
    Class driverClass = loader.loadClass('oracle.jdbc.OracleDriver') 
    Driver driverInstance = driverClass.newInstance() 
    java.sql.DriverManager.registerDriver(driverInstance) 

    Sql sql = Sql.newInstance('jdbc-url','username','password') 
} 
+0

我一直在使用相同的技巧爲MySQL,它的工作原理還有:http://stackoverflow.com/questions/6329872/how-to-add-external-jar-files-to-gradle-build-script – thoredge 2012-03-15 07:09:00

0

由於您使用gradle這個,你可以使用Groovy使其更短,更容易使用以及

def props = [:] 
def ds = new BasicDataSource() 
ds.with { 
    url = props['database.url'] 
    driverClassName = props['database.driverClassName'] 
    password = props['database.password'] 
    username = props['database.username'] 
} 

def sql = new groovy.sql.Sql(ds) 
def r = sql.firstRow 'select 1 as val from dual' 
println r.val 
相關問題