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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22604952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:47:17  来源:igfitidea点击:

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

javamysqljdbc

提问by rpires_098

I created an application that writes data to the database every 5 minutes.

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

However after some time this error appears:

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

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

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

I've been searching around and tells you to close the connection to the database after every request side.

我一直在四处寻找并告诉您在每个请求端之后关闭与数据库的连接。

I tried this:

我试过这个:

conexao.close();

But it gives me this error:

但它给了我这个错误:

No operations allowed after conection closed.

No operations allowed after conection closed.

I apologize if the question is not well formulated.

如果问题表述得不好,我深表歉意。

Thanks for the help

谢谢您的帮助

---------------------What I tried but didn't work---------------------------

---------------------我尝试过但没有用的东西--------------------- ------

Add

添加

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();
   }

回答by Keerthivasan

This kind of problem arises when you are NOTproperly closing the connection after usage.

当您在使用后没有正确关闭连接时,就会出现这种问题。

Please use finallyblock after catchto 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 finallyblock gets executed always. it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break

请使用finallyblock aftercatch适当关闭连接。这是因为即使出现意外异常或错误,也要确保连接正确关闭。请注意finally块内的语句总是被执行。它允许程序员避免通过 return、continue 或 break 意外绕过清理代码

Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

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

As you have asked in comment, I have added the code sample to demonstrate practically!

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

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();
}

Please note that the declaration of Connectionvariable should be in proper scope to close it in finallyblock.

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

Hope this helps!

希望这可以帮助!

回答by Vamshi Nagula

Restart apache tomcat server will work. This worked for me.

重启 apache tomcat 服务器即可。这对我有用。

Welcome

欢迎

回答by dirbacke

As from Java 7, java.sql.Connectionis AutoCloseable. From now on, you can write your code like this:

从 Java 7 开始,java.sql.ConnectionAutoCloseable. 从现在开始,您可以像这样编写代码:

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

}