Now I use gradle as my build tool. One of my tasks needs to access to a mysql database. Following is my gradle script:
import groovy.sql.Sql buildscript { dependencies { classpath files('/usr/share/java/mysql-connector-java.jar') } } task connectToDb << { def props = [user: 'user', password: 'password', allowMultiQueries: 'true'] as Properties def url = 'jdbc:mysql://mysqlhost:3306/db' def driver = 'com.mysql.jdbc.Driver' def sql = Sql.newInstance(url, props, driver) sql.eachRow('show tables') { row -> println row[0] } }
I try to run it in a Ubuntu Lucid box but it always fails. The gradle complains with the information: Execution failed for task ':connectToDb'. Cause: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
It seems that the build script doesn't include the mysql connector jar library.Can anyone please tell me how to configure the external jar file properly ? Thanks.
To add a dependency to your project, specify a dependency configuration such as implementation in the dependencies block of your module's build.gradle file.
This works for me. See this thread about why http://gradle.1045684.n5.nabble.com/using-jdbc-driver-in-a-task-fails-td1435189.html:
import groovy.sql.Sql repositories { mavenCentral() } configurations { driver } dependencies { driver group: 'mysql', name: 'mysql-connector-java', version: '5.1.16' } URLClassLoader loader = GroovyObject.class.classLoader configurations.driver.each {File file -> loader.addURL(file.toURL()) } task connectToDb << { def props = [user: 'user', password: 'password', allowMultiQueries: 'true'] as Properties def url = 'jdbc:mysql://mysqlhost:3306/db' def driver = 'com.mysql.jdbc.Driver' def sql = Sql.newInstance(url, props, driver) sql.eachRow('show tables') { row -> println row[0] } }
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