Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add external jar files to gradle build script

Tags:

gradle

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.

like image 940
Jeff Li Avatar asked Jun 13 '11 11:06

Jeff Li


People also ask

How do I add a dependency in gradle?

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.


1 Answers

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]     } } 
like image 180
thoredge Avatar answered Oct 01 '22 03:10

thoredge