• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question regarding PreparedStatement

 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I wonder what is the difference between the following 2 codes:





Both return the same result but I guess (and correct me if I�m wrong) that it is better to use the prepared statement (efficiency�but how, why?)

Thanks for any thoughts
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you pass a query into a database, it is just a string, the databse then does its own compilation to turn it into the DB query, performs a bunch of optimisation stuff and other database magic, then runs it.

When the Driver and database both support PreparedStatements, it links the query to the compiled and optimised bit in the database so that it doesn't need to happen all the time. I point this out since some Drivers mimic PS behaviour because it isn't supported in all DBs.

It is actually true that PreparedStatements are better most of the time, but it isn't really worth worrying about the other parts, it isn't enough of a difference to stop using them. This is because the database cannot fully optimise the query due to the unbound parts. I have seen stats showing that a single query with no variables can be more efficient, but this effect disappears as soon as you need to run the same query with a different value. Like I said, nothing to worry about.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15354
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first piece of code, where you construct an SQL statement by concatenating strings together, may introduce a security leak in your program - it may make your program vulnerable to SQL injection.

See this thread: http://www.coderanch.com/t/302647/JDBC/java/construct-SQL-statement
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic