mysql - 为什么在这种情况下有很多连接(MySQLNonTransientConnectionException)

标签 mysql select prepared-statement

我使用 PreparedStatement 进行选择时遇到异常。

Got an exception accessing TestCase data! null

Problem to connect.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:

Too many connections

这是我的代码:

public Integer getTypeByInputAndProblemId(String inputTestCase, Long problemId) {

    String sql = "SELECT type FROM test_case where problem_id= ? and input= ?";

    Integer type = 0;

    try {

        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setLong(1, problemId);
        ps.setString(2, inputTestCase);

        ResultSet rs = ps.executeQuery();

        if (rs.next()) {
            type = new Integer(rs.getInt("type"));
        }
        rs.close();
        ps.close();

    } catch (Exception e) {
        System.err.println("Got an exception accessing TestCase data! " + e.getMessage());
    }

    return type;
}

PreparedStatement ps = connection.prepareStatement(sql); 我的问题是因为连接有时为空(调试显示这一点)。

我猜这是因为有很多联系,但我不知道为什么会发生这种情况。

我需要一些帮助,请!

最佳答案

是的,出现此问题是因为您的服务器已达到 MySQL 服务器接受的最大多个连接数。

首先,您需要查看 MySQL 中是否为多个连接配置了正确的数字:max_connections如果您认为这个值很低,您可以增加此数字以“修复”此问题。

其次,如果这个数字有意义,那么您使用的连接数可能比您想象的要多。 可能是因为您在应用程序中打开连接而不是关闭它们。

检查您的服务器到目前为止使用了多少个多个连接。

show status like 'Max_used_connections';

当您重新启动数据库服务时,此数字将会重置。

关于mysql - 为什么在这种情况下有很多连接(MySQLNonTransientConnectionException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22852403/

相关文章:

php - 如何显示存储在我的数据库中的所有图像?

mysql - 如何让 MySQL case 语句在存储过程中工作?

MySQL 从有关系但没有连接的表中选择

mysql - 从四个表中选择计数

mysql - 跟踪多个相同的条目

mysql - 将无效的 ActiveRecord 日期插入 MySQL 数据库

mysql - 声明在 MySql 错误中创建触发器的变量

java - 与 Statement 对象的 setFetchSize 方法混淆

php - 何时使用 PDO exec() vs execute() vs query()

java - 选择参数=?但如果?是一个空格,返回该列的任何值