Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

PreparedStatement Vs Statement

 
Alec Lee
Ranch Hand
Posts: 569
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know in general we should use PreparedStatement. But is there any situation where Statement is prefered to PreparedStatement? Would it be okay if I just forget all about Statement and always stick to PreparedStatement?
 
Nikhil
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,
Yes it is always advisable to use PreparedStatement(PS) instead of Statement. There are reasons for that like
1) For each statement there will be a cursor created in DB(defly for oracle) and also for PreparedStatement. But if you use that PS in a loop then whose loops will be executed by only one cursor instead of the 'no of loop' cursors fir Statement. So you can avoid the 'max open cursor' problem in DB.

2) Performance will be better as well as the PS will be created once and 'soft soft parse' will be made onwards where as for each Statement the there is a possibility of doing hard parse.

Hope this helps.
Niks
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64629
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Nikhil",

We're pleased to have you here with us on the Ranch, but there are a few rules that need to be followed, and one is that proper names are required. Please take a look at the JavaRanch Naming Policy and adjust your display name to match it.

In particular, your display name must be a first and a last name separated by a space character, and must not be obviously fictitious.

Thanks!
bear
Forum Bartender
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While there are situations where Statements can outperform PreparedStatements*, in terms of general performance and ease of use it is almost always preferable to use PreparedStatements.

* just to clarify: in the case where you want to load one record from a table and you only ever load that one record, either a Statement or a PreparedStatement with no variables to bind will be faster than the generic solution because it gets compiled into more specific database-side code and the database is free to use every optimisation trick it knows. But, this case is not that common and you'd probably have to run it a million times to tell the difference. My advice is to stick with PreparedStatements.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic