I'm trying to set up the database with a gradle task. But I'm not having any luck getting it to find the postgresql JDBC driver. In the java project, it finds the driver and runs fine (and it doesn't get dependencies through buildscript though), but not the gradle.build file.
I tried using groovy.sql, and was greeted with the same error.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.postgresql:postgresql:42.2.0'
}
}
import java.sql.*
task testTask {
...
This line throws an error: No suitable driver found for jdbc:postgresql://localhost:5432/db
Connection conn = DriverManager.getConnection(db.url, db.user, db.password)
...
}
I got an answer from a post by Evelino Bomitali. He explains it concise. Do check the post he is referencing out too.
The code I'm using with Postgresql:
import groovy.sql.Sql
task queryTest () {
configurations {
jdbc
}
dependencies {
jdbc 'org.postgresql:postgresql:42.2.0'
}
doLast {
def sqlClassLoader = Sql.classLoader
configurations.jdbc.each { sqlClassLoader.addURL it.toURI().toURL() }
def driver = 'org.postgresql.Driver'
def dburl = "jdbc:postgresql://localhost:5432/testdb"
def first
Sql.withInstance(dburl, 'tester', 'password', driver) {
sql ->
first = sql.firstRow( "SELECT * FROM users" )
}
}
}
Buildscript does not have to be declared before the task now, since the dependencies are solved within the task.
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