gpt4 book ai didi

java - 如何从 Gradle 中的脚本连接到 MySQL

转载 作者:行者123 更新时间:2023-11-29 02:18:48 24 4
gpt4 key购买 nike

我想通过 build.gradle 连接到 MySQL 我不想从一些指定的文件夹中选择驱动程序,如下面的注释行 //loader.addURL(file(JDBC_ARCHIVE_PATH).toURL ())。我希望它像这样从 build.gradle 中指定的依赖项中选择驱动程序dependencies { compile 'mysql:mysql-connector-java:5.1.37' } 我该怎么做?

task loadDriver {
URLClassLoader loader = GroovyObject.class.classLoader
//loader.addURL(file(JDBC_ARCHIVE_PATH).toURL())
java.sql.DriverManager.registerDriver(loader.loadClass(analyticsDriverClassName).newInstance())
}

// Connect to the database
// The task expects the following properties:
// * analyticsDbUrl
// * analyticsDbUsername
// * analyticsDbPassword
task callDatabase() {
println "Connecting to database '$analyticsDbUrl' with user '$analyticsDbUsername' ..."
def sql = groovy.sql.Sql.newInstance(analyticsDbUrl, analyticsDbUsername, analyticsDbPassword)
println '... connected'
}

最佳答案

buildscript{
repositories{
jcenter()
}

dependencies{
classpath 'mysql:mysql-connector-java:5.1.37'
}
}

task something()<<{
def mysql = buildscript.configurations.classpath.find { it.toString().contains("mysql-connector-java") }
URLClassLoader loader = GroovyObject.class.classLoader
loader.addURL(file(mysql).toURL())

def db = [url: "jdbc:mysql://127.0.0.1/mydb?",
user: "root", password: "password", driver: 'com.mysql.jdbc.Driver']
def sql = groovy.sql.Sql.newInstance(db.url, db.user, db.password, db.driver)
}

关于java - 如何从 Gradle 中的脚本连接到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35032936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com