Jenkins-MySQL查询的主动选择

时间:2018-07-09 23:47:44

标签: mysql database jenkins groovy jenkins-plugins

与詹金斯(Jenkins)初次接触,并尝试使用常规脚本来获得一个主动的choices参数,但运气不佳。运行构建时,参数下拉列表始终为空。我的常规脚本如下:

import groovy.sql.Sql

def output = []

def sql = Sql.newInstance('jdbc:mysql://localhost:3308/information_schema', 'jenkins', 'password', 'com.mysql.jdbc.Driver')
String sqlString = "select schema_name from information_schema.schemata;"
sql.eachRow(sqlString){ row ->  
    output.push(row[0])
}


return output

我要去哪里错了?有没有办法查看groovy脚本的输出,以便查看它是否甚至与数据库建立了连接?

在此先感谢您的帮助/建议

1 个答案:

答案 0 :(得分:0)

您可以尝试如下操作:

import groovy.sql.Sql

//describe the DB connection params
def db = [
        url:'jdbc:mysql://localhost:3306/information_schema',
        user:'root',
        password:'',
        driver:'com.mysql.jdbc.Driver']

//New connection
def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)

def output = []
//query
String sqlString = "select schema_name from information_schema.schemata"
sql.eachRow(sqlString){ row ->
  output.push(row.schema_name)
}
//clean up
sql.close()

如果您愿意,您现在可以在里面窥视:

//Check what's up
String[] dbs = output as String[]

println dbs

输出在我的机器上是这样的:

[information_schema, mysql, ******, performance_schema, sys]

如果由于某种原因无法连接到数据库,那么您将获得异常。更多文档here

在您的Jenkins管道中,您可以使用ChoiceParameterDefinition。这样的东西(免责声明-未测试):

stage('Ask DB') {

    echo "Collecting user input about the DB..."

    String[] dbs = ...;//collect DB-s here

    //define the choice
    userChoice = new ChoiceParameterDefinition('targetDB',
            dbs,//<-- Pass array here!
            'Choose wisely your DB!')

    def targetDB = input(
            id: 'target-db',
            message: 'What is the DB?',
            parameters: [userChoice])

    echo "Input collected, proceeding for DB [${targetDB}]"
  }