如何在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异常.
我想从我的Gradle构建脚本运行一个groovy命令行脚本.
我在Gradle脚本中使用此代码:
def groovyShell = new GroovyShell();
groovyShell.run(file('script.groovy'), ['arg1', 'arg2'] as String[])
Run Code Online (Sandbox Code Playgroud)
在我的Groovy脚本(script.groovy)使用CliBuilder类之前,工作正常.然后我得到以下异常:
org.codehaus.groovy.runtime.InvokerInvocationException:java.lang.NoClassDefFoundError:org/apache/commons/cli/ParseException ...由以下引起:java.lang.ClassNotFoundException:org.apache.commons.cli.ParseException
我发现很多人有类似的问题和错误,但"解决方案"很难从我读过的众多帖子中提取出来.很多人建议将commons-cli jar放在类路径上,但对GroovyShell这样做对我来说并不是很明显.另外,我已经在script.groovy中为我所需的库声明了@Grapes和@Grab,所以它应该拥有它所需的一切.