【问题标题】:How to connect mysql database in groovy using connection parameters from command line?如何使用命令行中的连接参数在 groovy 中连接 mysql 数据库?
【发布时间】:2017-04-14 20:05:19
【问题描述】:

我需要从 Groovy 脚本连接我的 MySQL 数据库。 由于此脚本的目的是用于数据库更新,并对其进行细微更改;我需要能够使用 jar 文件提供必要的连接参数。我想动态输入连接参数,如 dbUrl、dbUsername 和 dbPassword,以便我可以根据数据库输入这些参数。下面的代码成功连接到数据库,但它是手动的。如果我必须用于“test”以外的其他数据库,我必须为每个数据库创建 jar 文件。

我对 groovy 比较陌生,任何帮助/建议将不胜感激。

我该怎么做?

 import groovy.sql.Sql
 import java.sql.*
 import java.io.File

  Sql sql
  def cities = []
 try{
    def url= 'jdbc:mysql://localhost:3306/test'
    def username = 'username'
    def password = 'password'
    def driver = 'org.mariadb.jdbc.Driver'
    sql = Sql.newInstance( url, username, password, driver)
    sql.eachRow("select * from City where city are not null"){cities += it.city}
    }catch(ClassNotFoundException | SQLException e){
           e.printStackTrace
    }

【问题讨论】:

    标签: mysql groovy


    【解决方案1】:

    执行以下脚本:

    groovy dbscript jdbc:mysql://localhost:3306/test username password
    

    dbscript.groovy

     import groovy.sql.Sql
     import java.sql.*
     import java.io.File
    
    if ( args.size() != 3 ) {
        println 'Please supply DB URL, username and password'
        System.exit(0)
    }
    
     Sql sql
     def cities = []
     try{
        def url= args[0]
        def username = args[1]
        def password = args[2]
        def driver = 'org.mariadb.jdbc.Driver'
        sql = Sql.newInstance( url, username, password, driver)
        sql.eachRow("select * from City where city are not null"){cities += it.city}
        }catch(ClassNotFoundException | SQLException e){
               e.printStackTrace
        }
    

    【讨论】:

    • 感谢您的帮助 Mike W.
    • @Sam,如果答案有帮助,您需要考虑接受它作为答案。
    • @Rao,我找不到办法。
    • 你的意思是答案没有帮助?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多