groovy 在Gradle任务中执行SQL?

x33g5p2x  于 2022-12-26  发布在  其他
关注(0)|答案(5)|浏览(251)

如何在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
    }
}

我得到一个java.lang.类未发现异常:org.postgresql.Driver执行sql任务时异常

tsm1rwdh

tsm1rwdh1#

要定义构建脚本本身的外部依赖项,必须将其放入构建脚本的类路径中,可以在buildscript闭包中定义它。

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'postgresql:postgresql:9.0-801.jdbc4'
    }
}
piv4azn7

piv4azn72#

如果你不介意依赖其他工具,你可以在你的项目中使用dbdeploy,还有一个gradle plugin可以让你导入SQL脚本。

pprl5pva

pprl5pva3#

buildscript {
    dependencies {
        classpath 'com.oracle:ojdbc6:11.2.0.3'
    }
}

task tmp() {
    dependsOn configurations.batch
    doLast {
        ant.sql(classpath: buildscript.configurations.classpath.asPath,
            driver: "oracle.jdbc.OracleDriver",
            url: "${dbConn}", userid: "${dbUser}", password: "${dbPass}",
            "select 1 from dual")
    }
}

或者:

ant.sql(classpath: buildscript.configurations.classpath.asPath,
        driver: "oracle.jdbc.OracleDriver",
        url: "${dbConn}", userid: "${dbUser}", password: "${dbPass}") {
    fileset(dir: dir) {
        include(name: "**/*.sql")
    }
}
ovfsdjhp

ovfsdjhp4#

找到了runsql-gradle-plugin,它允许执行自定义Gradle任务中定义的SQL脚本文件。
将这些字符串添加到我的 build.gradle.kts 后:

plugins {
    id("com.nocwriter.runsql") version ("1.0.3")
}

task<RunSQL>("initData") {
    dependencies {
        implementation("org.postgresql:postgresql")
    }
    config {
        url = "jdbc:postgresql://localhost:5432/test"
        driverClassName = "org.postgresql.Driver"
        username = "test"
        password = "test"
        scriptFile = "data.sql"
    }
}

我可以通过以下方式执行 data.sql

./gradlew initData
yzuktlbb

yzuktlbb5#

这里有一种方法:

gradle.class.classLoader.addURL(new File('../../../../lib/server/mssql/sqljdbc4.jar').toURI().toURL())
def Sql sql = Sql.newInstance(dbConnectionURL, dbUserName, dbPassword, dbDriverName)
String sqlString = new File(dbSchemaFile as String).text

sql.execute(sqlString)

相关问题