【问题标题】:Failed to connect Azure Database using Java(JDBC)使用 Java(JDBC) 连接 Azure 数据库失败
【发布时间】:2019-07-16 14:09:04
【问题描述】:

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

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

【问题讨论】:

  • 您的异常陷阱已被注释掉。如果它正在扔一个,它正在被吞下。如果它没有被吞下,它可能包含很多很好的信息来告诉你发生了什么。
  • 感谢大家。我能够连接数据库。它显示“时区”错误。我遵循了这样的 Stirng url: String url ="jdbc:mysql://:3306/?useSSL=true&requireSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";

标签: java azure jdbc azure-mysql-database


【解决方案1】:

就像对 cme​​ts 和我的附加内容的总结。

正如@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;
  2. 在连接字符串中添加附加参数?useTimezone=true&amp;serverTimezone=UTC,强制对JDBC连接会话使用相同的时区值。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    相关资源
    最近更新 更多