Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Statement and PreparedStatement

 
selvi family
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am new to JDBC..

I got confused with Statement and PreparedStatement.

We can execute the parameterized query by using PreparedStatement object

query="select * from students where roleno = ?";
pst=connection.prepareStatement(query);
pst.setInt(1,1000)
rs=pst.executeQuery();

We can execute the same by using Statement object also.

query = "Select * from userinfo where urefitem = 1000";
st=connection.createStatement();
rs=st.executeQuery(query);

but what is the difference between these two...

I am not able to get the appropriate scenario to use Statement object and PreparedStatement object...When to use what?Is it possible to execute a stored procedure using Statement object?

pls update me...

thanks
selvi.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generally PreparedStatements are the way to go. What they offer over and above Statements is:
  • Performance. A PreparedStatament will normally be compiled and cached by the DB. Any subsequent calls will use the compiled version.
  • Parameter binding is a much easier way to deal with parameters. It handles all the issues with Date formatting and the need to escape characters in SQL. It is also generally a much more readable way of coding than the usual mess of string concatenation you tend to see with Statements.

  •  
    Jeanne Boyarsky
    author & internet detective
    Sheriff
    Posts: 35977
    422
    Eclipse IDE Java VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Selvi,
    For a stored procedure, you use a CallableStatement object.

    In general, I suggest using a PreparedStatement over a Statement unless you have a really good reason not to.
     
    selvi family
    Ranch Hand
    Posts: 39
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    thanks !!!
    My doubt is cleared..

    Selvi
     
    What are you doing? You are supposed to be reading this tiny ad!
    the new thread boost feature brings a LOT of attention to your favorite threads
    https://coderanch.com/t/674455/Thread-Boost-feature
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!