Could not create connection to database server. Attempted reconnect 3 times

4,942 阅读1分钟

概述

在使用JDBC链接(Springboot 链接)数据库的时候,报错:Could not create connection to database server. Attempted reconnect 3 times. Giving up.

image.png

分析

数据库连接失败,检查url设置是否出现错误,主要包括ip,端口以及数据库名称。在我的错误中,以上原因都不是,而是数据库时区设置错误。

解决

  • 可能1:数据库名字错,检查数据库名字是否填写错误
  • 可能2:时区设置错误,在url后面添加上以下属性,使用上海时区
serverTimezone=Asia/Shanghai&useServerPrepStmts=true
  • 完整的url写法:
String url="jdbc:mysql://127.0.0.1:3306/imooc-redbook-dev?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true";

其他

以下代码可以用于快速测试数据库是否连接成功,用来快速判断问题。

  • 简单的数据库链接测试代码
    public static void jdbcall() throws ClassNotFoundException, SQLException {

        Class.forName("com.mysql.jdbc.Driver");//加载驱动类
        String url="jdbc:mysql://127.0.0.1:3306/imooc-redbook-dev?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true";
//        String url = "jdbc:mysql://127.0.0.1:3306/imooc-redbook-dev?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useServerPrepStmts=true&cachePrepStmts=true";
        String username="root";
        String password="root";
        Connection conn= DriverManager.getConnection(url,username,password);//用参数得到连接对象
        System.out.println("连接成功!");
        System.out.println(conn);
    }