繁体   English   中英

java jdbc中的连接太多

[英]Too many connection in java jdbc

错误:-严重:空com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:数据源拒绝建立连接,来自服务器的消息:“连接过多”代码如下所示

   try {
        BufferedReader br=new BufferedReader(new FileReader(filename));
        String line;
        String tru="TRUNCATE `project`.`uploadtable`;";
        try
       {
             Statement stmt = Dutil.getConnection().createStatement();



     stmt.executeUpdate(tru);
        }
        catch(Exception e){}
        try {
            while((line=br.readLine())!=null){
                String values[]=line.split("\t");
                String[] splitStr = values[1].split(" ");


               try {String  sql="INSERT INTO `project`.`uploadtable` 
            (`empid`, `date`, `time`, `in_out_index`) VALUES 
            ('"+values[0]+"', '"+splitStr[0]+"', '"+splitStr[1]+"', 
             '"+values[3]+"');";
                    PreparedStatement 
                   pst=Dutil.getConnection().prepareStatement(sql);
                    pst.executeUpdate();
                } catch (SQLException ex) {
                    System.out.println("Error");

             Logger.getLogger(UploadFrame.class.getName()).log(Level.SEVERE, 
              null, ex);
                }
            } br.close();

             this.dispose();
           LogButtonFrame lbf=new LogButtonFrame();
          lbf.clockinouttable();
           JOptionPane.showMessageDialog(null,"Upload Complete");} catch 
           (IOException ex) {
            Logger.getLogger(UploadFrame.class.getName()).log(Level.SEVERE, 
          null, ex);
            }
             } catch (FileNotFoundException ex) {
           Logger.getLogger(UploadFrame.class.getName()).log(Level.SEVERE, 
            null, ex);
          }
          catch (Exception ex) {
         JOptionPane.showMessageDialog(null, "Error");
        }

问题是:

PreparedStatement pst = Dutil.getConnection().prepareStatement(sql);

您尚未显示Dutil的代码,但假设它在每次调用时都创建了一个新连接,这意味着该连接没有被关闭,让它运气,驱动程序实现细节以及通过垃圾回收器将其关闭。

相反,您应该使用try-with-resources

try (Connection connection = Dutil.getConnection();
     PreparedStatement pst = connection.prepareStatement(sql)) {
    // Use pst
}

在此块结束之后,即使发生异常等, pstconnection都将被正确关闭。

您似乎正在创建连接,并且从不关闭它们,尽管很难从所摆出的图像中分辨出来。

如果您的应用程序需要多个连接,则应使用诸如Apache DB连接池之类的连接池,您可以在其中配置连接数。 这是DBCP文档的链接https://commons.apache.org/proper/commons-dbcp/

如果确定应用程序仅需要一个连接,则将连接对象设为DBUtil类中的Singleton对象。 这肯定可以解决问题,而无需关闭连接。 您的整个应用程序将使用单个连接对象连接到DB。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM