Could not connect to the database using JDBC driver


(Rupinder Ghotra) #1

Continuing the discussion from Is it possible to execute sql scripts via gradle and get responses if the execution was successful or not?:

I am using exactly the same thing as mentioned in this topic. Following is my code:

buildscript {
       repositories {
        flatDir name: 'localRepository', dirs: 'lib'
    }
    configurations {
        driver
    }
    dependencies {
        driver group: 'sql', name: 'sqljdbc42'
    }
}

URLClassLoader loader = GroovyObject.class.classLoader
configurations.driver.each { File file ->
    loader.addURL(file.toURL())
}

task connectToCoreDb << {
    def props = [user: 'sa', password: 'shock', allowMultiQueries: 'true'] as Properties
    def connectionUrl = "jdbc:sqlserver://cpt-op-01-db1:1433;databaseName=buds"
    def driver = 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
    def sql = Sql.newInstance(connectionUrl, props, driver)
    logger.info "Closing connection..."
    sql.close()
}

Please help me in this as I am stuck on this error for a very long time. It is throwing this error:

Caused by: org.gradle.api.internal.MissingMethodException: Could not find method
driver() for arguments [{group=sql, name=sqljdbc42}] on org.gradle.api.internal


(Rupinder Ghotra) #2

Found the solution, it was failing because I needed to define ‘driver’ dependency’s version(though it does not exist). Following is the working code:

buildscript {
       repositories {
        flatDir name: 'localRepository', dirs: 'lib'
    }
    configurations {
        driver
    }
    dependencies {
        driver group: 'sql', name: 'sqljdbc42', version:''
    }
}

URLClassLoader loader = GroovyObject.class.classLoader
configurations.driver.each { File file ->
    loader.addURL(file.toURL())
}

task connectToCoreDb << {
    def props = [user: 'sa', password: 'shock', allowMultiQueries: 'true'] as Properties
    def connectionUrl = "jdbc:sqlserver://cpt-op-01-db1:1433;databaseName=buds"
    def driver = 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
    def sql = Sql.newInstance(connectionUrl, props, driver)
    logger.info "Closing connection..."
    sql.close()
}