Fullmenu null

 

31 August 2017

The easiest case to explain is when we have several scripts in which there is a function/action that is repeated in each of them and every time we create a new script we must include it. This repetitive action can be a database connection, export to excel or simply contain the data of the database connection.

Next we will create a script called Configuration.groovy which will contain all the necessary information to connect at our environment database. This configuration can be called from any of our scripts, in this way we will avoid having to copy and paste that part of code.

Configuration.groovy
import Sql

class Configuration {

        String user     = "user"         //(1)
        String passwd   = "passwd"       //(2)
        String server   = "localhost"    //(3)
        String database = "test"         //(4)
        String url      = "jdbc:mysql://$server:3306/$database?jdbcCompliantTruncation=false"    //(5)

        def instanceMysql(){  //(6)
            return Sql.newInstance( "jdbc:mysql://$server:3306/$database?jdbcCompliantTruncation=false", "$user", "$passwd", "com.mysql.jdbc.Driver")
        }
        def instanceMysql(my_user,my_passwd,my_server,my_database){ //(7)
            return Sql.newInstance( "jdbc:mysql://$my_server:3306/$my_database?jdbcCompliantTruncation=false", "$my_user", "$my_passwd", "com.mysql.jdbc.Driver")
        }
}
  1. Method that returns user to connect.

  2. Method that returns the password.

  3. Method that returns the server where we are going to connect.

  4. Method that returns the database.

  5. Method that returns the url to connect.

  6. Method that returns a mysql instance with already defined data.

  7. Method that returns a mysql instance with the data sent by parameter.

To obtain an instance we can do it in the following way:

Script.groovy
def sql = Configuration.instanceMysql()

Or with the connection data sent by parameter:

OtroScript.groovy
def my_user = "user",
def my_passwd = "passwd",
def my_server ="localhost"
def database = "test"
def my_sql = Configuration.instanceMysql(my_user,my_passwd,my_server,my_database)

Script
import Sql

class Configuration {

        String user     = "user"         //(1)
        String passwd   = "passwd"       //(2)
        String server   = "localhost"    //(3)
        String database = "test"         //(4)
        String url      = "jdbc:mysql://$server:3306/$database?jdbcCompliantTruncation=false"    //(5)

        def instanceMysql(){  //(6)
            return Sql.newInstance( "jdbc:mysql://$server:3306/$database?jdbcCompliantTruncation=false", "$user", "$passwd", "com.mysql.jdbc.Driver")
        }
        def instanceMysql(my_user,my_passwd,my_server,my_database){ //(7)
            return Sql.newInstance( "jdbc:mysql://$my_server:3306/$my_database?jdbcCompliantTruncation=false", "$my_user", "$my_passwd", "com.mysql.jdbc.Driver")
        }
}