在Gradle任务中执行SQL?

jam*_*man 12 sql groovy jdbc gradle

如何在Gradle任务中执行SQL?

configurations {
    compile
}
repositories {
    mavenCentral()
}
dependencies {
    compile 'postgresql:postgresql:9.0-801.jdbc4'
}
task sql << {
    driverName = 'org.postgresql.Driver'
    Class.forName(driverName)
    groovy.sql.Sql sql = Sql.newInstance(
        'jdbc:postgresql://localhost:5432/postgres', 
        'username', 
        'password', 
        driverName
    )
    sql.execute 'create table test (id int not null)'
    sql.execute 'insert into test (id) values(1)'
    sql.eachRow 'select * from test' {
        println it
    }
}
Run Code Online (Sandbox Code Playgroud)

我在执行sql任务时遇到 java.lang.ClassNotFoundException:org.postgresql.Driver异常.

Ben*_*hko 16

为构建脚本本身定义外部依赖项,必须将其放入构建脚本的类路径中.你可以通过在buildscript闭包中定义它来做到这一点.

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'postgresql:postgresql:9.0-801.jdbc4'
    }
}
Run Code Online (Sandbox Code Playgroud)