在 Gradle 任务中执行 SQL?
如何在 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
}
}
我得到一个 执行sql任务时出现java.lang.ClassNotFoundException: org.postgresql.Driver异常。
How can I execute SQL in a Gradle task?
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
}
}
I get a
java.lang.ClassNotFoundException: org.postgresql.Driver exception when executing the sql task.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(5)
枉心2024-12-16 05:34:28
发现 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
旧街凉风2024-12-16 05:34:28
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")
}
}
南…巷孤猫2024-12-16 05:34:28
这是一种方法:
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)
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
要定义 构建脚本的外部依赖项,您必须将将其放入构建脚本的类路径中。您可以通过在
buildscript
闭包中定义它来做到这一点。To define external dependencies for the build script itself you got to put it into the build scripts' classpath. You can do that by defining it within the
buildscript
closure.