This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes JDBC and the fly likes PreparedStatement or Statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "PreparedStatement or Statement" Watch "PreparedStatement or Statement" New topic
Author

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
Bartender

Joined: Dec 20, 2006
Posts: 2491
    
    8

Hi,

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
youtube channel
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: PreparedStatement or Statement
 
Similar Threads
Where is Prepared Statement actually stored ?
Queries regarding PreparedStatement
Difference between Statement/Prepared statement?
pre-compile and prepared statement
does OracleDriver really precompile a PreparedStatement?