Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing of a PreparedStatement between methods?

We all know that we should rather reuse a JDBC PreparedStatement than creating a new instance within a loop.

But how to deal with PreparedStatement reuse between different method invocations? Does the reuse-"rule" still count?

Should I really consider using a field for the PreparedStatement or should I close and re-create the prepared statement in every invocation (keep it local)? (Of course an instance of such a class would be bound to a Connection which might be a disadvantage in some architectures)

I am aware that the ideal answer might be "it depends".
But I am looking for a best practice for less experienced developers that they will do the right choice in most of the cases.

like image 812
MRalwasser Avatar asked Jan 10 '11 13:01

MRalwasser


2 Answers

Of course an instance of such a class would be bound to a Connection which might be a disadvantage

Might be? it would be a huge disadvantage. You'd either need to synchronize access to it, which would kill your multi-user performance stone-dead, or create multiple instances and keep them in a pool. Major pain in the ass.

Statement pooling is the job of the JDBC driver, and most, if not all, of the current crop of drivers do this for you. When you call prepareStatement or prepareCall, the driver will handle re-use of existing resource and pre-compiled statements.

Statement objects are tied to a connection, and connections should be used and returned to the pool as quickly as possible.

In short, the standard practice of obtaining a PreparedStatement at the start of the method, using it repeatedly within a loop, then closing it at the end of the method, is best practice.

like image 55
skaffman Avatar answered Oct 29 '22 01:10

skaffman


Many database workloads are CPU-bound, not IO-bound. This means that the database ends up spending more time doing work such as parsing SQL queries and figuring out how to handle them (doing the 'execution plan'), than it spends accessing the disk. This is more true of 'transactional' workloads than 'reporting' workloads, but in both cases the time spent preparing the plan may be more than you expect.

Thus it is always a good idea, if the statement is going to be executed frequently and the hassle of making (correct) arrangements to cache PreparedStatements 'between method invocations' is worth your developer time. As always with performance, measurement is key, but if you can do it cheaply enough, cache your PreparedStatement out of habit.

Some JDBC drivers and/or connection pools offer transparent 'prepared statement caching', so that you don't have to do it yourself. So long as you understand the behaviour of your particular chosen transparent caching strategy, it's fine to let it keep track of things ... what you really want to avoid is the hit on the database.

like image 30
David Bullock Avatar answered Oct 28 '22 23:10

David Bullock