MySQL connection remains after closing (), with a thin shell

I wrote a Java program that connects to a MySQL database, closes immediately, and then sleeps for a while to complete.

Connection conn = DriverManager.getConnection(conn_str); conn.close(); Thread.sleep(30 * 1000); 

The above code works very well. conn will be closed immediately after calling close (), and during sleep () no connection will appear.

After that, I wrote a thin shell connection:

  public static Connection CreateConnection(String _connectionStr) throws SQLException { Connection c = null; c = DriverManager.getConnection(_connectionStr); return c; } 

modified code:

  Connection conn = ConnectionWrapper.CreateConnection(conn_str); conn.close(); Thread.sleep(30 * 1000); 

I expect the two to be no different, but with the last case, the connection remained open until the program ended (30 seconds here). This does not happen in the previous code.

I checked the behavior with mysqladmin extend-status | grep connected mysqladmin extend-status | grep connected by looking at the value of Threads_connected .

I want to use the last shell to abstract code. Please tell me if you have an idea of ​​the behavior or workaround to force the connection to close.

Thanks,

-

Edited: The wrapper code has been fixed. That was my fault.

Edited: The default number of connections from mysqladmin is 1 (diagnostic). The number becomes 2 while the last code is running, and 2 with the first.

+4
source share
3 answers

You have the opportunity to try these codes ... and see what the error will output ...

 try{ con.close(); if (con.isClosed()) System.out.println("Connection closed."); } catch (java.lang.ClassNotFoundException e) { System.err.println("ClassNotFoundException: " +e.getMessage()); } catch (SQLException e) { System.err.println("SQLException: " +e.getMessage()); } 
0
source

I think this is pooling (the idea is to save time on reconnecting ...)

Take a look at this article:

http://dev.mysql.com/tech-resources/articles/connection_pooling_with_connectorj.html

0
source

OK, sorry for being so numb looking at your code ... as you can see ... you created a connection inside the method ... so that means when you exit this method ... you cannot close this connection (c variable) because you just copied the connection to another variable using the return (which is your conn variable) ... and still the connection remains. Try creating a class for your wrapper, not a method

-2
source

Source: https://habr.com/ru/post/1398562/


All Articles