无法使用 Java(JDBC) 连接 Azure 数据库

Failed to connect Azure Database using Java(JDBC)

我正在尝试使用 JDBC 连接我的 Azure 数据库。但它无法连接。服务器名、用户名、数据库名和密码我都用对了

使用 Mysql 连接器 v8.0.13

import java.sql.*;
import java.util.Properties;


public class MyConnection {

    public static Connection getConnection() {


        System.out.println("MySQL JDBC driver detected in library path.");

        Connection connection = null;

        try
        {


            String url ="jdbc:mysql://<servername>:3306/<databaseName>?useSSL=true&requireSSL=false"; 
            connection = DriverManager.getConnection(url, <username>, <password>);
        }
        catch (SQLException e)
        {
            //throw new SQLException("Failed to create connection to database.", e);
        }
        if (connection != null) 
        { 
            System.out.println("Successfully created connection to database.");

        }
        else {
            System.out.println("Failed to create connection to database.");
        }
        System.out.println("Execution finished.");


        return connection;
    }
}

我原以为会显示 "Successfully created connection to database." 但它显示 "Failed to create connection to database."

就像评论的摘要和我的附加内容。

正如@LomatHaider 所说,由 Java 代码引起的问题引发了有关时区的错误。根据MySQL官方文档MySQL Server Time Zone Support,如下

Time Zone Variables

MySQL Server maintains several time zone settings:

  • The system time zone. When the server starts, it attempts to determine the time zone of the host machine automatically and uses it to set the system_time_zone system variable. The value does not change thereafter.

    To explicitly specify the system time zone for MySQL Server at startup, set the TZ environment variable before you start mysqld. If you start the server using mysqld_safe, its --timezone option provides another way to set the system time zone. The permissible values for TZ and --timezone are system dependent. Consult your operating system documentation to see what values are acceptable.

  • The server current time zone. The global time_zone system variable indicates the time zone the server currently is operating in. The initial time_zone value is 'SYSTEM', which indicates that the server time zone is the same as the system time zone.

因此,如果从未为 MySQL 设置时区变量,则 MySQL 中的默认时区设置将遵循 OS 时区。据我所知,Azure 上的默认时区是 UTC,那么客户端连接 on-premise 或本地的时区可能会与 Azure 上的 MySQL 不同,冲突导致此问题信息如下.

java.sql.SQLException: The server time zone value 'Malay Peninsula Standard Time' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

所以修复它的解决方案是以下两个选项:

  1. 按照MySQL官方文档到SET GLOBAL time_zone = timezone;获得超级权限。
  2. 在连接字符串中添加附加参数 ?useTimezone=true&serverTimezone=UTC 以强制对 JDBC 连接会话使用相同的时区值。

有一篇博客MySQL JDBC Driver Time Zone Issue :: \[SOLVED\]介绍了与这个相同的问题,并通过上面的第二个选项修复它。