Using a connection for multiple methods in the same class and other methods

Asked

Viewed 33 times

2

Could I have only one connection and use it in several methods? For example:

The Prepared statement needs an open connection to run, so I do the getConnection(), and another method also needs, so I have to do another getConnection(), there would be no way to "optimize" this?

  • Type create a connection variable that will receive the getConnection()

1 answer

1


That’s essentially how it’s done. But it makes no difference, it’s already internally optimized. Note that it takes a connection, it doesn’t create a connection. Well, create if there isn’t one.

Of course, you can do this, store an object and pass it everywhere in the application, and there are people who like to do this (they say it makes the test easier, but it harms normal execution, they should use other solutions to facilitate the test). But what’s the difference?

You probably think this one getConnection() it’s something heavy, but it’s not, it’s pretty much the same as accessing something open.

Doing so alternative opens up possibilities of making some mistake and causing great confusion later and hard to find out where and why.

I kind of like the idea of not managing the connection, but you need to know how to do it right, and almost no one knows.

You can create a static attribute in the class that stores this connection and uses it all the time, but it’s 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 doing this it is best not to. And the gain would be derisory, the getConnection() is almost the same thing as what you’re going to do.

  • If I close the connection, every time I pick it up, will it change something? For example optimize?

  • 1

    The ideal is to close, otherwise you may have problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.