无法使用Java JDBC连接到MySQL数据库

3

我创建了一个简单的类来测试与本地主机数据库的通信,该数据库是我使用Mysql Workbench创建的。 Mysql服务器正在运行。 JDBC驱动程序已添加到我的项目的类路径中。

public class Database
{
    public static void main(String[] args)
            throws SQLException, ClassNotFoundException
    {
        Connection connection = null;
        String serverName = "localhost:3306";
        String databaseName = "detector_tests";
        String url = "jdbc:mysql://" + serverName + "/" + databaseName
                + "?useSSL=TRUE";

        String username = "simon";
        String password = "password123";
        connection = DriverManager.getConnection(url, username, password);
    }
}

运行程序时,我遇到了以下异常:

“main”线程中的异常com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure,表示通信链路失败。最近一次成功发送到服务器的数据包是0毫秒前发送的。驱动程序没有接收到来自服务器的任何数据包。原因是:com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure,最近一次成功发送到服务器的数据包是0毫秒前发送的,驱动程序没有接收到来自服务器的任何数据包。Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors,表示SSL握手失败,证书验证不通过。路径与受信任锚点的任何链接不匹配。

看起来我需要添加某种证书或类似的东西。因为我对数据库还比较新,所以不太确定。有没有和我有相同经验或者解决方案的人?如果需要更多信息,我很乐意编辑帖子。

提前感谢!


java.security.cert.CertificateException:java.security.cert.CertPathValidatorException:路径与任何信任锚点不匹配 - Mark Rotteveel
这是什么意思?我需要在我的Windows操作系统上配置Eclipse、数据库或其他什么东西吗? - skonline90
你试过谷歌搜索那个错误信息吗?我看到了很多帖子和回复... - Zephyr
是的,找不到任何有用的东西。 - skonline90
1个回答

2
似乎您正在尝试连接带有证书的mysql数据库。如果您通过TLS连接到MySQL实例,则需要拥有一个信任存储区来保存您的证书。请参考此文档以创建带有TLS连接的MySQL连接。
但是,您可以通过在MySQL连接URL中设置"useSSL"为FALSE来忽略TLS验证。您的代码将如下所示。

public class Database
{
    public static void main(String[] args)
            throws SQLException, ClassNotFoundException
    {
        Connection connection = null;
        String serverName = "localhost:3306";
        String databaseName = "detector_tests";
        String url = "jdbc:mysql://" + serverName + "/" + databaseName
                + "?useSSL=FALSE";

        String username = "simon";
        String password = "password123";
        connection = DriverManager.getConnection(url, username, password);
    }
}

希望这能回答你的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接