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

时间:2014-03-24 09:05:01

标签: java mysql jdbc

我创建了一个每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 个答案:

答案 0 :(得分:6)

NOT 在使用后正确关闭连接时,会出现此类问题。

  

请在finally之后使用catch阻止相应地关闭连接。这是因为即使出现意外异常或错误,也要确保连接正确关闭。请注意finally块内的语句始终执行。它允许程序员避免因返回,继续或中断而意外绕过清理代码

注意:如果在执行try或catch代码时JVM退出,则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块中关闭它。

希望这有帮助!

答案 1 :(得分:0)

从Java 7开始, <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript" ></script> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> java.sql.Connection。从现在开始,您可以像这样编写代码:

AutoCloseable

答案 2 :(得分:0)

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

检查mysql中max_connections的数量:

show variables like 'max_connections';

确保使用DB Max连接具有适当的打开连接值。

答案 3 :(得分:-2)

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

欢迎