File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes JDBC and the fly likes Should You Always Use PreparedStatement instead of Statement? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Should You Always Use PreparedStatement instead of Statement?" Watch "Should You Always Use PreparedStatement instead of Statement?" New topic
Author

Should You Always Use PreparedStatement instead of Statement?

Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

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

Joined: Oct 08, 2006
Posts: 2458
A query which doesn't require parameterized values can perfectly be executed using Statement.
Scott Selikoff
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3704
    
    5

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.


My Blog: Down Home Country Coding with Scott Selikoff
Bauke Scholtz
Ranch Hand

Joined: Oct 08, 2006
Posts: 2458
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

Joined: Nov 18, 2006
Posts: 689

Thank you for taking the time to answer my question.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Should You Always Use PreparedStatement instead of Statement?