首页 > 解决方案 > 尝试连接到远程 MySQL 数据库时出现 PakcetTooBigException

问题描述

我正在尝试从 Spring Boot 应用程序连接到我的远程 MySQL 数据库,并在一段时间内遇到此错误。

即使在增加 max_allowed_pa​​cket 大小之后,我也会收到此错误。

在此处输入图像描述

测试连接的简单类[ Mkyong ]

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCExample {

    public static void main(String[] argv) {

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }

        Connection connection = null;

        try {

            connection = DriverManager.getConnection("jdbc:mysql://HOST:PORT/DB", "user", "password");

        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
            return;
        }

        if (connection != null) {
            System.out.println("You made it, take control your database now!");
        } else {
            System.out.println("Failed to make connection!");
        }
    }
}

安慰:

Connection Failed! Check output console
com.mysql.jdbc.PacketTooBigException: Packet for query is too large (4739923 > 1048576). You can change this value on the server by setting the max_allowed_packet' variable.
    at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:578)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1014)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2190)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2221)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2016)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:776)

更新:

请注意,我已经增加了 max_allowed_pa​​cket 大小。目前尺寸为

mysql>  Select @@global.max_allowed_packet;
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
|                   536870912 |
+-----------------------------+
1 row in set (0.31 sec)

mysql>

标签: javamysqlspring-bootjdbcmariadb

解决方案


您需要在服务器中设置 max_allowed_pa​​cket 大小以避免此错误。设置参数后需要重启服务器。我不知道您使用的版本,因此请参阅以下链接以获取详细说明。

https://dev.mysql.com/doc/refman/8.0/en/packet-too-large.html


推荐阅读