I've added SQLite in build.gradle:
dependencies {
compile 'org.xerial:sqlite-jdbc:3.8.9.1'
}
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'org.xerial:sqlite-jdbc:3.8.9.1'
}
}
Once I want to connect to SQLite DB in code:
groovy.sql.Sql.newInstance(dbLocation, "org.sqlite.JDBC")
It complains that :
java.lang.ClassNotFoundException: org.sqlite.JDBC
What is the reason? How can I fix it?
The problem is that you need to get the JDBC drivers into the root classloader rather than just being on the generalised classpath.
You have a few options. One of them is to use your own configuration
, and then manipulate the root classloader via GroovyObject
:
import groovy.sql.Sql
configurations {
sqllite
}
repositories {
mavenCentral()
}
dependencies {
sqllite 'org.xerial:sqlite-jdbc:3.8.9.1'
}
URLClassLoader loader = GroovyObject.class.classLoader
configurations.sqllite.each { File file ->
loader.addURL(file.toURL())
}
Sql sql = Sql.newInstance('jdbc:sqlite:test.db', "org.sqlite.JDBC")
task checkSql << {
sql.execute 'CREATE TABLE TIM(name CHAR(50))'
sql.eachRow('SELECT * FROM sqlite_master') { row ->
logger.lifecycle row.toString()
}
}
Then running gradle checkSql
should result in:
$ gradle checkSql
:checkSql
[type:table, name:TIM, tbl_name:TIM, rootpage:2, sql:CREATE TABLE TIM(name CHAR(50))]
BUILD SUCCESSFUL
Total time: 4.374 secs
At least, it does in Gradle 2.9