1

I need to connect my MySQL database from Groovy script. Since the intend of this script is to use for db update with minor change in it; I need to able to supply the necessary connection parameters with jar file. I would like to input connection parameters such as dbUrl, dbUsername, and dbPassword dynamically so that I can input those as per database. Below code successfully connect to database, but it is manual. I have to create jar file for each database if I have to use for other database than 'test'.

I am relatively new to groovy, any help/suggestion would be appreciated.

How do I proceed with this?

 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
    }

1 Answer 1

1

Execute the script below with:

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
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your help Mike W.
@Sam, if the answer is helpful, you need to consider accepting it as answer.
@Rao, I couldn't find a way to do that.
You mean the answer isn't helpful?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.