"No suitable driver found for jdbc:sqlserver" when running Groovy Sql from Gradle

I’m trying to execute some SQL statements from a Gradle script against an MS SQL database.

My build script looks as follows:

import groovy.sql.Sql

apply plugin: 'groovy'

sourceCompatibility = 1.7

buildscript {
  repositories { 
    flatDir { dirs 'lib' } 
  }
  dependencies {
    classpath name: 'sqljdbc41'
  }
}

task execSql << {
  def db = [url:'jdbc:sqlserver://localhost:1433;databaseName=MyDatabase;', user:'sa', password:'', driver:'com.microsoft.sqlserver.jdbc.SQLServerDriver']
  def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)
  sql.execute("select * from mytable")
}

‘sqljdbc41’ is the JDBC driver provided from Microsoft.

When I execute ‘gradle execSql’ I get the following error: SQLException: No suitable driver found for jdbc:sqlserver

Here’s the relevant part of the stack trace:

    [...]
Caused by: java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost:1433;databaseName=MyDatabase;
    at build_6l4mta35kvubw7rvlc27wmcdg$_run_closure1.doCall(D:\Users\MyName\Documents\SW-Development\Gradle-Groovy\eclipse-ws\MsSqlGradleDemo\build.gradle:18)
    at org.gradle.api.internal.AbstractTask$ClosureTaskAction.execute(AbstractTask.java:558)
    at org.gradle.api.internal.AbstractTask$ClosureTaskAction.execute(AbstractTask.java:539)
    at org.gradle.api.internal.tasks.TaskMutator$1.execute(TaskMutator.java:77)
    at org.gradle.api.internal.tasks.TaskMutator$1.execute(TaskMutator.java:73)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    ... 57 more

It looks for me to be a classloader problem. Although the driver library is doubtless in the classpath (e.g. I can do Class.forName(‘com.microsoft.sqlserver.jdbc.SQLServerDriver’)), at a later stage it is somehow not accessible by the GroovyClassLoader.

When I put the three statements of the task into a Groovy script and call that script directly (not using Gradle), it works as expected.

Is there something wrong with my Gradle script? Or is there a (known?) issue with Gradle?

(Note: the issue can be reproduced as described above in any Win7 environment, an MS SQL server installation is not prerequisited)

1 Like

I am facing the exact same issue.

@Nepomuk The driver needs to be loaded in the same ClassLoader as Groovy. Have a look at this forum post: Is it possible to execute sql scripts via gradle and get responses if the execution was successful or not?

@Adrian_Kelly Thanks for the hint, this works indeed, but is this the solution?! Looks rather as a workaround to me…