有 Java 编程相关的问题?

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

java错误:数据源拒绝建立连接,来自服务器的消息:“连接太多”

我创建了一个应用程序,每5分钟向数据库写入一次数据

但是,一段时间后会出现此错误:

Error: Data source rejected establishment of connection, message from server: "Too many connections"

我一直在四处搜索,并告诉您在每次请求结束后关闭与数据库的连接

我试过这个:

conexao.close();

但它给了我一个错误:

No operations allowed after conection closed.

如果这个问题没有很好的表述,我很抱歉

谢谢你的帮助

---------我试过但没有成功---------------------------

finally{ 
    if(conexao!=null)
   conexao.close();
   }

  Class.forName("com.mysql.jdbc.Driver");
        Connection conexao = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/bdTeste", "root", "root");
        Statement stm = conexao.createStatement();
        BufferedReader reader = new BufferedReader(new FileReader("C:/Users/RPR1BRG/Desktop/test.txt"));

        String dados[] = new String[6];
        String linha = reader.readLine();

        while (linha != null) {

            StringTokenizer st = new StringTokenizer(linha, ";\"");

            dados[0] = st.nextToken();
            dados[1] = st.nextToken(); 
            dados[2] = st.nextToken();
            dados[3] = st.nextToken();
            dados[4] = st.nextToken();
            dados[5] = st.nextToken();

             DateFormat dateFormat = new SimpleDateFormat("d-M-yy");

    PreparedStatement stmt = (PreparedStatement) conexao.prepareStatement("replace into registos"
    + " (data_registo, hora_registo, IdSensor, Temperatura, Humidade, pt_orvalho) values (?,?,?,?,?,?)");
                    try {
                        stmt.setDate(1, new java.sql.Date(dateFormat.parse(dados[0]).getTime()));
                        stmt.setString(2, dados[1]);
                        stmt.setString(3, dados[2]);
                        stmt.setString(4, dados[3]);
                        stmt.setString(5, dados[4]);
                        stmt.setString(6, dados[5]);

                    } catch (java.text.ParseException ex) {
                        Exceptions.printStackTrace(ex);
                    }


stmt.executeUpdate();

            linha = reader.readLine();
            PrintWriter writer = new PrintWriter("C:/Users/RPR1BRG/Desktop/test.txt"); 
            writer.print("");
            writer.close();
            Verifica();
            }

    } catch (ClassNotFoundException | SQLException | IOException e) {

        System.err.println("Erro: " + e.getMessage());

    }finally{ 
    if(conexao!=null)
   conexao.close();
   }

共 (4) 个答案

  1. # 1 楼答案

    从Java7开始,java.sql.ConnectionAutoCloseable。从现在起,您可以这样编写代码:

    try(Connection con = (Connection) DriverManager.getConnection(url, username, pazzword)) {
       //your statements
    }catch(RuntimeException e) {
    
    }
    
  2. # 2 楼答案

    这可能是因为配置的max_connections不适合JDBC中设置的连接池大小或针对DB打开的连接数

    要检查mysql中的max_connections数量,请执行以下操作:

    show variables like 'max_connections';
    

    确保使用DB Max connections打开的连接的值正确

  3. # 3 楼答案

    重新启动ApacheTomcat服务器将正常工作。这对我有用

    欢迎光临

  4. # 4 楼答案

    如果使用后未正确关闭连接,则会出现此类问题

    Please use finally block after catch to close the connections appropriately. This is because to ensure that the connection gets closed properly even when there is an unexpected exception or error. Please note that statements inside finally block gets executed always. it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break

    注意:如果JVM在执行try或catch代码时退出,那么finally块可能不会执行。同样,如果执行try或catch代码的线程被中断或终止,那么即使整个应用程序继续运行,finally块也可能不会执行

    正如您在评论中所问的,我添加了代码示例以实际演示

    Connection con = null
    try{
     //Establishing connection to datasource
     con = DBConnection.getConnection();
     //perform DB operations
     ...
     ...
     ...
    }catch(SQLException sqlEx){
     /*To catch any SQLException thrown during DB 
      *Operations and continue processing like sending alert to admin
      *that exception occurred.
      */
    }finally{
     /*This block should be added to your code
      * You need to release the resources like connections
      */
     if(con!=null)
      con.close();
    }
    

    请注意Connection变量的声明应该在适当的范围内,以便在finally块中关闭它

    希望这有帮助