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.
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.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'postgresql:postgresql:9.0-801.jdbc4'
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With