This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Should You Always Use PreparedStatement instead of Statement?

 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have heard that when you use an object of the class Statement, that your software is vulnerable to SQL injection. It seems like the Statement class should never be instantiated, and instead, you should always instantiate a PreparedStatement instead (which is a subclass of Statement).

I can't think of any use of having the Statement class anymore except that it is a super-class to PreparedStatement.

Am I right in thinking this?
 
Bauke Scholtz
Ranch Hand
Posts: 2458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A query which doesn't require parameterized values can perfectly be executed using Statement.
 
Scott Selikoff
author
Saloon Keeper
Posts: 4020
18
Eclipse IDE Flex Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you should (see this blog post, tip #2). There's a big difference between "what could be done" and "what should be done". In short, it makes your code a lot easier to maintain should you decide to add parameters later on. Even if you don't parametrize the query, prepared statements may be pre-compiled by the JDBC driver, meaning call the same PreparedStatement object 10x could (or rather should) be faster than calling the same Statement object using the same query 10x.

In general, you should always use PreparedStatement's over Statements.
 
Bauke Scholtz
Ranch Hand
Posts: 2458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
He was asking this in perspective of SQL injections.

But indeed, a PreparedStatement is faster than a Statement. That's another reason of preferring it over Statement. Another more reason is that it really eases setting non-standard Java objects such as Date and InputStream in a SQL string. You just use PreparedStatement#setDate() and #setBinaryStream() instead. No hassle with nasty conversions.
 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for taking the time to answer my question.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic