Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle buildscript doesn't find Postgresql JDBC driver [duplicate]

Tags:

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) 
 ...
}
like image 616
Mikk Avatar asked Jan 24 '18 12:01

Mikk


1 Answers

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.

like image 150
Mikk Avatar answered Sep 19 '22 15:09

Mikk