【问题标题】:Error: Data source rejected establishment of connection, message from server: "Too many connections"错误:数据源拒绝建立连接,来自服务器的消息:“连接太多”
【发布时间】:2014-05-01 13:07:43
【问题描述】:

我创建了一个应用程序,它每 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();
   }

【问题讨论】:

  • 这段代码被调用了多少次?我怀疑你在没有关闭它们的情况下创建了很多连接
  • 感谢回复:我每 5 分钟调用一次此代码以读取文件并写入数据库。我试图关闭连接,但给了我另一个错误:“连接关闭后不允许任何操作。”

标签: java mysql jdbc


【解决方案1】:

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

请在catch 之后使用finally 块来适当地关闭连接。这是因为即使出现意外异常或错误,也要确保正确关闭连接。请注意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 块中关闭它。

希望这会有所帮助!

【讨论】:

  • 感谢您的回复。我想我知道你在说什么,但我可以用更实际的方式解释一下吗?非常感谢。
  • 再次非常感谢您。我试试你说的,但过去一段时间给我同样的错误。 “连接关闭后不允许任何操作。”
  • 请完整发布相关的更新代码
  • 请正确编辑您的问题以获得帮助。它不可读。
  • 好的,你是不是多次调用close()方法?
【解决方案2】:

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

欢迎

【讨论】:

  • 即使你重启你的Tomcat实例,你还是会遇到同样的问题。不如写好代码。
【解决方案3】:

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

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

}

【讨论】:

    【解决方案4】:

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

    在mysql中检查max_connections的数量:

    show variables like 'max_connections';
    

    确保您在 DB Max 连接中打开的连接具有适当的值。

    【讨论】:

      猜你喜欢
      • 2012-08-18
      • 2011-08-12
      • 2015-04-03
      • 2011-03-13
      • 2016-10-28
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      相关资源
      最近更新 更多