现在我使用gradle作为构建工具。我的一个任务需要访问mysql数据库。以下是我的gradle脚本:
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]
}
}
我尝试在Ubuntu Lucid框中运行它,但它总是失败。 gradle抱怨信息: 任务':connectToDb'的执行失败。 原因:java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
似乎构建脚本不包含mysql连接器jar库。任何人都可以告诉我如何正确配置外部jar文件?感谢。
答案 0 :(得分:42)
这对我有用。请参阅此主题,了解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]
}
}
答案 1 :(得分:10)
我有幸这样的事情:
buildscript {
dependencies {
classpath fileTree(dir: '/usr/share/java',
includes: ['mysql-connector-java.jar'])
}
}
但坦率地说,在你的情况下,我更喜欢这个:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'mysql:mysql-connector-java:5.1.16'
}
}
答案 2 :(得分:0)
以下代码段适用于在 Microsoft SQL SERVER 中连接和查询数据库。请注意,Microsoft不会在任何在线仓库(如MavenCentral())上提供jar文件&#39; sqljdbc42.jar&#39;(这是jdbc驱动程序)。因此,您需要从Microsoft的网站下载此jar并保存在项目工作区目录中。 Download 'sqljdbc_4.2.6420.100_enu.exe'
解压缩下载的文件并转到用于SQL Server的Microsoft JDBC驱动程序4.2 - &gt; sqljdbc_4.2 - &gt; enu 。在这里,您将看到文件 sqljdbc42.jar 。将文件复制到项目工作区。我复制到目录名称&#39; lib&#39; 。
repositories {
flatDir name: 'localRepository', dirs: 'lib'
}
configurations {
driver
}
dependencies {
driver group: 'sql', name: 'sqljdbc42', version:''
}
URLClassLoader loader = GroovyObject.class.classLoader
configurations.driver.each { File file ->
loader.addURL(file.toURL())
}
task connectToCoreDb << {
def props = [user: 'sa', password: 'shock', allowMultiQueries: 'true'] as Properties
def connectionUrl = "jdbc:sqlserver://cpt-op-01-db1:1433;databaseName=buds"
def driver = 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
def sql = Sql.newInstance(connectionUrl, props, driver)
sql.eachRow('SELECT name, alias, expiry_date FROM [buds].[dbo].[obj_keystore] ) { row ->
println "$row.name $row.alias $row.expiry_date"
}
logger.info "Closing connection..."
sql.close()
}