[JAVA] [PostgreSQL] The story that you have to cut the session properly

One day

When I tried to connect to PostgreSQL as usual, I got this error.

FATAL: sorry, too many clients already

?? You shouldn't be apologized. It seems that the client has exceeded the DB settings ...

I doubt again here. That shouldn't be the case because I'm just using it for testing.

For the time being, check with select * from pg_stat_activity;.

1234 datname.hoge 0000 postgres 000.000.0.000 2020/1/29 00:00 1234 datname.hoge 0000 postgres 000.000.0.000 2020/1/29 00:00 1234 datname.hoge 0000 postgres 000.000.0.000 2020/1/29 00:00 ... 100 cases below

Yeah ... I'm sorry I used it. This is like sorry.

As a cause. When making continuous DB connections with the Java program on the server side you are using

db.java


try {
    Class.forName("org.postgresql.Driver");
    conn = DriverManager.getConnection(DBURL, user, password);
    Statement stmt = conn.createStatement();
    String sql = "First SQL statement";
    ResultSet rs = stmt.executeQuery(sql);
    rs.close();
    stmt.close();
}catch (SQLException e){
}catch (Exception e){
}

try {
    Class.forName("org.postgresql.Driver");
    conn = DriverManager.getConnection(DBURL, user, password);
    Statement stmt = conn.createStatement();
    String sql = "Second SQL statement";
    ResultSet rs = stmt.executeQuery(sql);
    rs.close();
    stmt.close();
}catch (SQLException e){
}catch (Exception e){
}finally{
    try{
        if (conn != null){
            conn.close();
        }
    }catch (SQLException e){
      	    //Exception handling
    }
}

I just closed it at the end, but I have to do it every time. It was a matter of course. It's too hot.

Recommended Posts

[PostgreSQL] The story that you have to cut the session properly
Have you ever thought about the definition of "bad design"?
[PostgreSQL] The story that you have to cut the session properly
A memorandum of the FizzBuzz problem
Completely delete the migration file that you failed to delete
I have summarized the articles that programming beginners referred to.
[PostgreSQL] If you want to delete the Rails app, delete the database first!
The story of Collectors.groupingBy that I want to keep for posterity
The story I wanted to unzip
To you who lament that the conversion of JODConverter + LibreOffice is slow
We have released a service that allows you to easily create chats!
A story that was embarrassing to give anison file to the production environment
[Rails] Display people who have DMed on My Page so that you can link to the chat page! 【memorandum】
[Java] Are you reading the error message properly? [How to read the stack trace]
Defense Techniques When You Have to Fight the Performance of Unfamiliar Applications (Part 2)