Use a connection for several methods in the same class and in others

2

Would you like to have only one connection and use it in multiple methods? For example:

The prepared statement needs an open connection to run, so I do getConnection() , and another method also needs, so I have to do another getConnection() , I would not like to "optimize" this ?

    
asked by anonymous 17.12.2017 / 08:43

1 answer

1

Essentially this is how it is done. But it makes no difference, it is already internally optimized. Note that it takes a connection, it does not create a connection. Well, create if there is not one.

Of course, you have to do this, store an object and pass it all over the application, and there are people who like to do this (they say it makes testing easier, but it hurts normal execution, they should use other solutions to facilitate the test). But what's the difference?

You probably think this getConnection() is heavy, but it's not, it's pretty much the same as getting access to something open.

Doing this way opens up possibilities to make some mistake and cause great confusion later and difficult to find out where and why.

I even like the idea of not managing the connection, but you need to know how to get it right, and almost nobody knows.

You can create a static attribute on the class that stores this connection and use it all the time, but it is very easy to keep the connection active longer than necessary and create problems in other classes, without a thorough knowledge of all the implications of to do this is better not to do. And the gain would be negligible, getConnection() is almost the same as what you're going to do.

    
17.12.2017 / 11:24