如何将 JDBC 驱动程序添加到 Jenkins 管道?

2021-12-23 00:00:00 jenkins mysql jdbc groovy jenkins-pipeline

我想在管道脚本中创建一个数据库,供部署的应用程序使用.但首先我开始测试连接.我遇到了这个问题:

I want to create a database within a pipeline script to be used by the deployed app. But first I started testing the connection. I got this problem:

java.sql.SQLException: No suitable driver found for jdbc:mysql://mysql:3306/test_db

我已经安装了数据库插件和 MySQL 数据库插件.

I have the database plugin and the MySQL database plugin installed.

如何获取 JDBC 驱动程序?

How do I get the JDBC driver?

import groovy.sql.Sql
node{

    def sql = Sql.newInstance("jdbc:mysql://mysql:3306/test_db", "user","passwd", "com.mysql.jdbc.Driver")
    def rows = sql.execute "select count(*) from test_table;"
    echo rows.dump()
}

在 albciff 回答后更新:

我的版本:

Jenkins = 2.19.1

Database plugin = 1.5

Mysql database plugin = 1.1

最新的测试脚本.

import groovy.sql.Sql

Class.forName("com.mysql.jdbc.Driver")

抛出:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver 

推荐答案

来自 MySQL 数据库插件 文档您可以看到 MySQL 的 jdbc 驱动程序包括在内:

From the MySQL DataBase Plugin documentation you can see that jdbc drivers for MySQL are included:

请注意,MySQL JDBC 驱动程序在 GPLv2 下,但有 FOSS 例外.这插件本身符合 FOSS 例外的条件,但如果您是重新分发此插件,请检查许可条款.Drizzle(+MySQL) 数据库插件可作为替代插件,那个是在 BSD 许可下的.

Note that MySQL JDBC driver is under GPLv2 with FOSS exception. This plugin by itself qualifies under the FOSS exception, but if you are redistributing this plugin, please do check the license terms. Drizzle(+MySQL) Database Plugin is available as an alternative to this plugin, and that one is under the BSD license.

更具体地说,此插件的实际最新版本 (1.1) 包含连接器版本 5.1.38:

More concretely the actual last version (1.1) for this plugin contains connector version 5.1.38:

1.1 版(2016 年 5 月 21 日)mysql-connector 5.1.38 版

Version 1.1 (May 21, 2016) mysql-connector version 5.1.38

因此,可能为了使驱动程序可用,您必须强制注册驱动程序.

So probably in order to have the driver available you have to force the driver to be registered.

在你的代码中实例化连接之前使用Class.forName("com.mysql.jdbc.Driver"):

To do so use Class.forName("com.mysql.jdbc.Driver") before instantiate the connection in your code:

import groovy.sql.Sql
node{
    Class.forName("com.mysql.jdbc.Driver")
    def sql = Sql.newInstance("jdbc:mysql://mysql:3306/test_db", "user","passwd", "com.mysql.jdbc.Driver")
    def rows = sql.execute "select count(*) from test_table;"
    echo rows.dump()
}

更新:

为了在 Jenkins 管道 groovy 脚本中使用 JDBC 连接器类,您需要更新 DataBase 插件 到最新版本:

In order to has the JDBC connector classes available in the Jenkins pipeline groovy scripts you need to update the DataBase plugin to last currently version:

1.5 版(2016 年 5 月 30 日)管道支持

Version 1.5 (May 30, 2016) Pipeline Support

相关文章