James.Wyst
James.Wyst

Reputation: 849

Cannot connect to DB2 from Groovy

I’m trying to open an SQL instance within a driver which uses the DB2Driver from IBM.

The interesting part is that when I include:

def DB2Driver = new DB2Driver()

That initializes just fine.

But when I do

 Sql.newInstance(info.getHost(), info.getConnectionMetaData().getParameterValue('username'), info.getConnectionMetaData().getParameterValue('password'), info.getConnectionMetaData().getParameterValue('driverClass'))

Or

Sql.newInstance(info.getHost(), info.getConnectionMetaData().getParameterValue('username'), info.getConnectionMetaData().getParameterValue('password'), 'com.ibm.db2.jcc.DB2Driver')

It will fail to open a SQL connection, saying that a suitable driver isn't found. How can I get the connection to DB2 to open?

Upvotes: 1

Views: 1721

Answers (1)

jalopaba
jalopaba

Reputation: 8119

Assuming that you are using a groovy script with @Grab and @Grapes annotations, you probably need configure Grape for JDBC drivers:

Because of the way JDBC drivers are loaded, you’ll need to configure Grape to attach JDBC driver dependencies to the system class loader

In groovy.sql.Sql the JDBC DriverManager is used to get a connection: DriverManager.getConnection(). Since it needs the driver depencencies attached to the system class loader, you need to do it with @GrabConfig.

For example, this script

@Grapes([
  @Grab(group='org.hsqldb', module='hsqldb', version='2.3.2'),
])

import groovy.sql.Sql

def sql = Sql.newInstance('jdbc:hsqldb:mem:testdb', 'sa', '', 'org.hsqldb.jdbcDriver')

println 'SQL connection ready'

fails with the exception java.sql.SQLException: No suitable driver found for jdbc:hsqldb:mem:testdb, but with

@Grapes([
  @Grab(group='org.hsqldb', module='hsqldb', version='2.3.2'),
  @GrabConfig(systemClassLoader=true)
])

it works perfectly.

Upvotes: 1

Related Questions