首页 > 解决方案 > 使用 Java(JDBC) 连接 Azure 数据库失败

问题描述

我正在尝试使用 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;
    }
}

我期待显示“成功创建与数据库的连接”。但它显示“无法创建与数据库的连接”。

标签: javaazurejdbcazure-mysql-database

解决方案


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

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

时区变量

MySQL 服务器维护几个时区设置:

  • 系统时区。当服务器启动时,它会尝试自动确定主机的时区,并使用它来设置 system_time_zone 系统变量。此后该值不会改变。

    要在启动时显式指定 MySQL 服务器的系统时区,请在启动 mysqld 之前设置 TZ 环境变量。如果您使用 mysqld_safe 启动服务器,它的 --timezone 选项提供了另一种设置系统时区的方法。TZ 和 --timezone 的允许值取决于系统。请查阅您的操作系统文档以查看可接受的值。

  • 服务器当前时区。全局 time_zone 系统变量表示服务器当前运行所在的时区。 time_zone 初始值为 'SYSTEM',表示服务器时区与系统时区相同。

因此,如果从未为 MySQL 设置 Time Zone 变量,则 MySQL 中的默认时区设置将遵循 OS 时区。据我所知,Azure 上的默认时区是 UTC,那么客户端连接本地或本地的时区可能与 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;SUPER 权限为准。
  2. 在连接字符串中添加附加参数?useTimezone=true&serverTimezone=UTC以强制对 JDBC 连接会话使用相同的时区值。

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


推荐阅读