有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

尝试连接到远程MySQL数据库时出现java PakcetTooBigException

我试图从Spring Boot应用程序连接到我的远程MySQL数据库,但有一段时间我遇到了这个错误

即使在增加了允许的最大数据包大小之后,我也会遇到这个错误

enter image description here

测试连接的简单类[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)

更新:

请注意,我已经增加了允许的最大数据包大小。目前尺寸为

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

mysql>

共 (2) 个答案

  1. # 1 楼答案

    在mysql控制台中更改如下设置:

    SET GLOBAL max_allowed_packet = 1024*1024*14;
    

    然后再次尝试连接

    更新: 你可以检查这个线程:How to change max_allowed_packet size

    希望这对你有帮助