问题
I'm getting this error Cannot open a new connection because existing connection is still on current thread
after a while. I think the error is pretty self explanatory. My code is this:
String mySQLUrl = "jdbc:postgresql://" + dataLayer.PostgreSQL_Host + "/" + dataLayer.PostgreSQL_Database;
Base.open("org.postgresql.Driver", mySQLUrl, dataLayer.getPostgreSQLUser(), dataLayer.getPostgreSQLPassword());
In order to avoid that error, i would like to create a connection factory, but to accomplish this, i need to know how to verify if there's a connection opened (and still valid) and return it, otherwise, create it. Is there something built or should i use the good old try-catch? :|
回答1:
If you are getting this exception, then that means that you still have a connection on the current Thread while opening a new one. This type of code may lead to a connection leak, so the framework prevents you from doing so.
This page: http://javalite.io/database_connection_management#thread-connection-propagation explains that models find a connection on the current thread.
Since you are not providing any context for your application, I will give you a couple of examples.
If this is a batch application (standalone app), you need to open a connection, use it then close:
try(DB db = Base.open(...)){
// your code here
}
This will ensure that the connection is closed and removed from a current thread.
If you are using ActiveWeb, then you can use the DBConnectionFilter
:
http://javalite.io/database_configuration
As in any web app, you would open a connection (pull from the connection pool) before a request is processed, use the connection in your controller, then close a connection (return to pool) at the end of a request.
If you are not using ActiveWeb, you can write a simple Servlet Filter that will do the same, here is one example: ActiveJdbcFilter
来源:https://stackoverflow.com/questions/48493247/cannot-open-a-new-connection-because-existing-connection-is-still-on-current-thr