Win a copy of Node.js Design Patterns: Design and implement production-grade Node.js applications using proven patterns and techniques this week in the Server-Side JavaScript and NodeJS forum!
    Bookmark Topic Watch 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
The JavaDoc:java.sql.PreparedStatement class offers three important benefits over JavaDoc:java.sql.Statement. These are:

1) Security

Prepared statements offer a measure of protection against what is known as SQL injection attacks. This means that by using prepared statements you are preventing malicious users from inserting values to search for that are actually SQL commands that do harm to the database.

For example, consider a SQL statement like this:

If the String value was something like "a';TRUNCATE table;"

bad things might be about to happen.

Our JDBC Forum has this interesting discussion on some of the ways to prevent SQL injection

2) Formatting Portability

The implementing driver is responsible for handling the conversion and formatting issues of data in queries. Issues like how to handle ' in text values, how to format date values and how to express boolean values are all handled by Prepared Statements.

Prepared statements make this issue go away and handle it in a manner independent of your code. This means the code has better portability which may be an important consideration. A few times unlucky souls have posted existing code that has hard-coded formatting, and a change in the backend database vendor -or even sometimes version- broke the code.

3) Performance Benefits

Due to the way prepared statements are pre-parsed before execution using them usually will result in increased performance. This performance factor will vary wildly for a number of reasons including the type of RDBMS, the driver and the operation being performed.

The two extreme ends are that there may not be any performance improvement whatsoever (or in fact it may be slower to execute one statement vs the other) to being exponentially faster to execute repeating statements because the RDBMS not only parses the SQL but prepares and caches the query plan for execution as well.

    Bookmark Topic Watch Topic
  • New Topic