• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Actual difference between PreparedStatement and Statement

 
Sunesh Kumar
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please say me the actual diffrenece between the Statement and PreparedStatement class usad\ge .I think there will be no diff and but why PreparedStatemet is using as a wide range.

Sorry for my poor English and Thanks in advance
 
purushottaman dwarkanathan
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The advantage of using a PreparedStatement over a Statement object is that
the SQl code is pre-compiled as compared to a Statement object.

When you create the PreparedStatement the SQL query is passed to it

like this

Connection con = DriverManager.getConnection();

PreparedStatement ps = con.getPrepareStatement("Select * from <table name> where id = ?");

ps.setInt(1,"200");

ResultSet rs = ps.executeQuery();


in the case of a statement object

it is like this

Statement st = con.createStatement();

ResultSet rs = st.executeQuery(" select * from <table name>");

In the second part the ResultSet is getting created after the query is fired. In case there is an error in the query, the ResultSet will be an issue. This is an advantage in the PreparedStatement as the query is compiled earlier and also it is dynamic, as you can set the values to the placeholder on the fly.

Thanks,

Purushottaman
 
Syed Munazzar Ali
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to me the preparedStatement is more powerfull version of statement.

-->PreparedStatement interface accepts Input Parameters at Runtime where as Statement interface cannot accept.
--> If you plan to use SQL Statement many times then go for preparedStatement.
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch, Syed!

We have a wiki page on the subject, which, I believe, lists the most important benefits nicely.

Syed Munazzar Ali wrote: --> If you plan to use SQL Statement many times then go for preparedStatement.

I'd suggest using PreparedStatement always. You save a lot of time not deciding between the two each time you need it.

Furthermore, in multiuser applications with connection pools there really aren't statements that aren't used many times. PreparedStatements are (or at least can and should be) cached by connection pools, so even if certain statement is executed by each user at most once, the cached version can still be used to serve multiple users. This is very often overlooked when assessing performance implications of (not) using PreparedStatement.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic