简体   繁体   English

JAVA:MySql:连接过多

[英]JAVA: MySql: too many connection

I think that my application is cursed, debug goes where it wants and I don't know why. 我认为我的应用程序很受诅咒,调试可以在需要的地方进行,我不知道为什么。 Line by line debugging seems to analyze also the commented rows. 逐行调试似乎也可以分析注释的行。 I think that the problems are on my Connection method, I see a significant performance slowdown, and at the third (or fourth nvm) connection I get this error: 我认为问题出在我的Connection方法上,我发现性能显着下降,在第三个(或第四个nvm)连接上,出现此错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Too many connections

I'm sure that I close the connection each time I've access to the DB (with finally statement out of the try catch in the implementation). 我确定每次访问数据库时都会关闭连接(在实现中的try catch中使用finally语句)。

Here's my connection class: 这是我的连接类:

package Connection;

import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.rmi.RemoteException; import java.sql.*; import java.util.Properties;

public class ConnectionDB {         
    public static ResultSet rs = null;  
    public static Statement stat = null;    
    public static Connection cn = null;

    public static void connect() throws RemoteException     {
            String dbHost="",dbUser="",dbPassword="";
            Properties prop=new Properties();
            try
            {
                //carico il file:
                prop.load(new FileInputStream("***/config.properties"));
                //Leggo le proprietà del file:
                dbHost=prop.getProperty("host");
                dbUser=prop.getProperty("user");
                dbPassword=prop.getProperty("password");
            }catch(FileNotFoundException fe){
                System.out.println("config file not found");
            }catch(IOException ex){
                System.out.println("Error reading config file");
            }
            try 
            {
                String driver = "com.mysql.jdbc.Driver";
                Class.forName(driver);
                dbHost = "jdbc:mysql://"+dbHost;
                cn = DriverManager.getConnection(dbHost,dbUser,dbPassword);
                stat = cn.createStatement();
            }catch(SQLException e){
                System.out.println("Can't connect to the DB");
            }
            catch(ClassNotFoundException cln){
                System.out.println("Error using JDBC driver");
            }   
    }   

    public static void disconnect() throws RemoteException  {
            try{
                if(rs != null) rs.close();
                if(stat != null) stat.close();
                if(cn != null) cn.close();
            }
            catch(SQLException sqlEx){
                System.out.println("Error: disconnect");
            }   
      }
}

The disconnect method may need following enhancement. 断开连接方法可能需要进行以下增强。 In this one, we close ResultSet, Statement & Connection separately. 在这一节中,我们分别关闭ResultSet,Statement和Connection。 This will save from situation where individual exception will not result into not closing the connection object. 这样可以避免个别异常不会导致不关闭连接对象的情况。

public static void disconnect() throws RemoteException {
        try{
            if(rs != null) rs.close();
        }
        catch(SQLException sqlEx){
            System.out.println("Error: disconnect");
        }   


        try{
           if(stat != null) stat.close();
        }
        catch(SQLException sqlEx){
            System.out.println("Error: disconnect");
        }   

        try{
            if(cn != null) cn.close();
        }
        catch(SQLException sqlEx){
            System.out.println("Error: disconnect");
        }   
  }

There're a couple of options that I think you can try out: 我认为您可以尝试以下几种方法:

  • As in the comments provided, you can increase the max number of connections allowed . 如提供的注释中所示,您可以增加允许的最大连接数

  • You talked about performance degradation. 您谈到了性能下降。 If this has to do with number of connection open, I would suggest that you consider reusing your connection. 如果这与打开的连接数有关,建议您考虑重新使用连接。 In this scenario using a connection pool might be of help. 在这种情况下,使用连接池可能会有所帮助。 This might be of help in this case. 在这种情况下, 这可能会有所帮助

If you're using a developer version of your database it probably has a restriction on the number of connections that can be made. 如果您使用的是数据库的开发人员版本,则可能会对可建立的连接数量有所限制。 So you'll need to manage them better which means that you should make sure they are closed when you've finished with them. 因此,您需要更好地管理它们,这意味着您应该确保在完成处理后将其关闭。 ( EDIT : just realised you're using mysql so this shouldn't be an issue) 编辑 :刚意识到您正在使用mysql,所以这应该不是问题)

Also, you mentioned that your debugger is going through comments - this is typically the case where your code is out of synch with your build. 另外,您提到调试器正在注释中-这通常是代码与构建不同步的情况。 Clean your build (in eclipse it would be Project > clean ... > clean all projects) and that problem should disappear. 清理您的构建(在月食中将是Project> clean ...> clean all projects),该问题应消失。

Normally there is limited number of connections available for user. 通常,用户可用的连接数量有限。 Additionally, establishing connections is costly operation. 另外,建立连接是昂贵的操作。 Therefore, if you experience performance problems you should start using connection pool, discussion about connection pools 因此,如果遇到性能问题,应该开始使用连接池, 有关连接池的讨论

Regarding your code, make sure you always release connections in finally block. 关于您的代码,请确保始终在finally块中释放连接。 Also we don't know what kind of queries you run. 另外,我们也不知道您运行哪种查询。 Print your queries and try running them manually in mysql and see if the problems is your SQLs, not Java. 打印查询并尝试在mysql中手动运行它们,看看问题是否出在您的SQL而不是Java。 Also you never close FileInputStream meaning you can run out of file handlers. 另外,您永远不会关闭FileInputStream,这意味着您可能会用完文件处理程序。

In case you run the same statement in a loop consider using PreparedStatements and batch updates and transactions. 如果您在循环中运行同一条语句,请考虑使用PreparedStatements以及批处理更新和事务。 If you use transactions, make sure you don't have much data in uncommitted state. 如果使用事务,请确保未提交状态下没有太多数据。

If you want to analyze performance of your queries you can use JAMon (Java Application Monitor) 如果要分析查询的性能,可以使用JAMon(Java应用程序监视器)

Suggestion to increase number of connections is similar to advising a person with diarrhea to eat more food. 关于增加人际关系的建议类似于建议腹泻的人多吃食物。

Try this 尝试这个

if(cn == null){
    String driver = "com.mysql.jdbc.Driver";
    Class.forName(driver);
    dbHost = "jdbc:mysql://"+dbHost;
    cn = DriverManager.getConnection(dbHost,dbUser,dbPassword);
}

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

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