File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes PreparedStatement or Statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "PreparedStatement or Statement" Watch "PreparedStatement or Statement" New topic

PreparedStatement or Statement

santhosh.R gowda
Ranch Hand

Joined: Apr 06, 2009
Posts: 296
Dear All

As we know PreparedStatement are pre-compiled statement and hence the compile time will get reduced when we are in loop of quieres.and now i'm having only one query to execute(Select or inser or update) which statement is good Statement or preparedStatement at first both will take the same time next when another thread access the query will it reduce the compile time in prepared statement or what..?

Creativity is nothing but Breaking Rules
Jan Cumps

Joined: Dec 20, 2006
Posts: 2565


You should use a PreparedStatement for all but the most simple queries.
There are several reasons:

PreparedStatement allows you to bind parameters. You do not have to paste sql queries together, e.g.:
Statement: "select myresult from mytable where myid = " + myId + " and myClass = '" + myClass + "'"
PreparedStarement: "select myresult from mytable where myid = ? and myclass = ?"

PreparedStatement prevents sql injection (look this up on the web, lots of info to be found)

PreparedStatement takes care of escaping issues: Try to write a Statement query where you want to insert a string with double quotes in it, like: Tom says "How are you?"

If you execute a PreparedStatement twice, database recognises it as two times the same statement. Execution plan can be reused.
If you execute a Statement twice, with one value in the where clause different, database thinks it is a new query, and starts to analyse it all over.

As we know PreparedStatement are pre-compiled statement and hence the compile time will get reduced
Depends on your driver / database. This is not a given.

OCUP UML fundamental and ITIL foundation
I agree. Here's the link:
subject: PreparedStatement or Statement
It's not a secret anymore!