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?
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.
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.