14

The following Groovy script fails with a java.lang.ClassNotFoundException: com.mysql.jdbc.Driver exception.

@Grapes([
    @Grab('mysql:mysql-connector-java:5.1.25')
])

import groovy.sql.Sql

def sql = Sql.newInstance(
    'jdbc:mysql://localhost/books', 
    'root',
    '', 
    'com.mysql.jdbc.Driver'
);

I looked into the JAR file stored at C:\Users\Dusan\.groovy\grapes\mysql\mysql-connector-java\jars\mysql-connector-java-5.1.25.jar and it contains the Driver class.

What can be wrong?

Dušan Rychnovský
  • 11,699
  • 8
  • 41
  • 65

2 Answers2

25

You need:

@GrabConfig(systemClassLoader = true)

After your @Grab, and just:

@Grab('mysql:mysql-connector-java:5.1.25')
@GrabConfig(systemClassLoader = true)
import groovy.sql.Sql

def sql = Sql.newInstance(
    'jdbc:mysql://localhost/books', 
    'root',
    '', 
    'com.mysql.jdbc.Driver'
)

Should do

tim_yates
  • 167,322
  • 27
  • 342
  • 338
1

How do you use it in groovysh ?

As per the doc, Grab is used in the shell this way

groovy.grape.Grape.grab([group:'mysql:mysql-connector-java:5.1.25'])

I haven't found the equivalent for @GrabConfig. It simply does not work inside groovysh.