问题描述
现在我使用gradle作为我的构建工具。我的一个任务需要访问mysql数据库。以下是我的gradle脚本: import groovy.sql.Sql
buildscript {
依赖关系{
classpath files('/ usr / share / java / mysql-connector-java.jar')
}
}
任务connectToDb << {
def props = [user:'user',password:'password',allowMultiQueries:'true'] as
def url ='jdbc:mysql:// mysqlhost:3306 / db'
def driver ='com.mysql.jdbc.Driver'
def sql = Sql.newInstance(url,props,driver)
sql.eachRow('show tables'){行 - >
println row [0]
}
}
我试试在Ubuntu Lucid框中运行它,但总是失败。 Gradle抱怨信息:
任务':connectToDb'的执行失败。
原因:java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
似乎构建脚本不包含mysql连接器jar库。任何人都可以请告诉我如何正确配置外部jar文件?谢谢。
这适用于我。请参阅此主题以了解:
import groovy.sql.Sql
仓库{
mavenCentral()
}
配置{
驱动
}
依赖关系{
驱动程序组:'mysql',名称:'mysql-connector-java',版本:'5.1.16'
}
URLClassLoader loader = GroovyObject.class .classLoader
configurations.driver.each {文件文件 - >
loader.addURL(file.toURL())
}
任务connectToDb<< {
def props = [user:'user',password:'password',allowMultiQueries:'true'] as
def url ='jdbc:mysql:// mysqlhost:3306 / db'
def driver ='com.mysql.jdbc.Driver'
def sql = Sql.newInstance(url,props,driver)
sql.eachRow('show tables'){行 - >
println row [0]
}
}
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.
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]
}
}
这篇关于如何将外部jar文件添加到gradle构建脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!