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?
ClassNotFoundException in Java? ClassNotFoundException is a checked exception and occurs when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath. In older days, there are no editors like Eclipse are available.
lang. NoClassDefFoundError, which means the Class Loader file responsible for dynamically loading classes can not find the . class file. So to remove this error, you should set your classpath to the location where your Class Loader is present.
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
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.
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