• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

question regarding PreparedStatement

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
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.
Java Cowboy
Posts: 16084
Android Scala IntelliJ IDE Spring Java
  • 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: https://coderanch.com/t/302647/JDBC/java/construct-SQL-statement
Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic