Java中的“Too Many Connections”错误(MYSQLNonTransientConnectionException)

时间:2015-05-03 07:18:50

标签: java mysql jdbc

我想将本地驱动器的每个文件名插入到mysql数据库中。

当我执行此代码时,它会完美地启动。

读取文件名目录的代码:

public void main(String[] args)throws IOException {
    JOptionPane.showMessageDialog(null, "IT MAY TAKE SOMETIME TO LOAD \n PLEASE WAIT FOR CLOSING POPUP!!");
    String s="D:\\";

    Path startingDir = Paths.get(s);        
    String pattern="*";
    Finder finder = new Finder(pattern);
    Files.walkFileTree(startingDir, finder);

    JOptionPane.showMessageDialog(null,"close\n NOW PLEASE CLICK\nSEARCH MY FILE! BUTTON");

这是将结果插入数据库的代码:

public void find(Path file) {

Path name = file.getFileName();
String st = file.toString();
if (name != null && matcher.matches(name)) {
    try {

        Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/login","root","");
        conn.createStatement();
        String query =" INSERT INTO `search`(`path`) VALUES (?)";
        PreparedStatement pst=conn.prepareStatement(query);
        pst.setString(1,st );
        pst.execute();

        //myst.executeUpdate(query);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(null, e);
    }

一段时间后,脚本将停止此异常

com.mysql.jdbc.exception.jdbc4.MYSQLNonTransientConnectionException:
Data source rejected establishment of connection,
message from server:"Too Many connections"

有什么方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:8)

对于每个插入,您都可以创建新连接。如果你继续这样做,他们会建立并最终耗尽与数据库的连接。这个限制可能非常小,例如20。

相反,你可以

  • 关闭您使用过的资源。这意味着关闭PreparedStatementConnection
  • 或更高效地创建一个Connection和一个PrepareStatement 永远并重复使用它。节省了必须创建和清理可能很昂贵的资源(除非驱动程序为您进行此回收)

答案 1 :(得分:2)

简单的解决方法是在执行查询后关闭连接。

pst.close();
conn.close();

这应该完成工作。 但重用连接会更好。

相关问题