【问题标题】:How to keep the connection to the MySQL database?如何保持与 MySQL 数据库的连接?
【发布时间】:2020-11-28 16:31:22
【问题描述】:

我正在尝试修复 MySQL 数据库的连接问题。几个小时后,我的服务器意外关闭了与 MySQL 数据库的连接。

这是我的错误代码:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:从服务器成功接收到的最后一个数据包是 37,521,865 毫秒前。最后一个成功发送到服务器的数据包是在 37,521,865 毫秒前。比服务器配置的“wait_timeout”值长。您应该考虑在应用程序中使用之前使连接失效和/或测试连接有效性,增加客户端超时的服务器配置值,或使用 Connector/J 连接属性“autoReconnect=true”来避免此问题。

这是我的 MySQL java 代码:

public class MySQL {

public static String host = "localhost";
public static String port = "3306";
public static String database = "SignSystem";
public static String username = "SignSystem";
public static String password = "12345678910";
public static Connection con;

public static void connect() {
    if (!(isConnected())) {
        try {
            con = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username, password);
            System.out.println("[MySQL] Connected successfully!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

public static void disconnect() {
    try {
        con.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

public static boolean isConnected() {
    return (con == null ? false : true);
}

public static void update(String qry) {
    if (!(isConnected())) {
        try {
            con = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username, password);
            System.out.println("[MySQL] Connected successfully!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    try {
        PreparedStatement ps = con.prepareStatement(qry);
        ps.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    } else {
        try {
            PreparedStatement ps = con.prepareStatement(qry);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

public static ResultSet getResult(String qry) {
    
    try {
        PreparedStatement ps = con.prepareStatement(qry);
        return ps.executeQuery();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}

public static Connection getConnection() {
    return con;
}

}

我已经尝试通过在执行任务之前检查数据库是否已连接来解决此问题。 但似乎我的修复不起作用。

如何解决此错误? 我想要自动重新连接或稳定连接。

【问题讨论】:

  • this 工作吗?
  • 或者可以将?autoReconnect=true添加到jdbc url
  • 使用连接池。让它测试连接。它(正确地)解决了您的问题,并有可能使您的应用程序更具可扩展性。

标签: java mysql server connection


【解决方案1】:

如果您正在寻找稳定的连接,请尝试在您的连接字符串上设置:

con = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database+"?autoReconnect=true", username, password);

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2010-11-30
    • 2016-12-17
    • 1970-01-01
    • 2016-10-08
    相关资源
    最近更新 更多