title: Difference between CreateStatement and PreparedStatement in JDBC
body: <p>Hi I am trying to learn JDBC.
  and here is my question:-</p>
  
  <p>What is the Use of <code>PreparedStatement</code> in JDBC Because We can achieve the same effect by using <code>createStatement();</code> too.</p>
  
  <p>I mean if there is a query like:</p>
  
  <pre><code>Select * from tbl_name where id = somevalue
  </code></pre>
  
  <p>Then We can achieve it by both <code>PreparedStatement</code> and <code>createStatement()</code>. As follows:</p>
  
  <p>Using <code>CreateStatement()</code>:</p>
  
  <pre><code>try {
        DataInputStream dis=new DataInputStream(System.in);
        System.out.println("Enter id :- ");
        int id=Integer.parseInt(dis.readLine());
        String q="Select * from tbl_name where id="+id;
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(q);
        while(rs.next()) {
           //fetching part
       }
  } catch(Exception ex){  ...  }
  </code></pre>
  
  <p>Using <code>PreparedStatement</code>:</p>
  
  <pre><code> try {
          PreparedStatement preStatement=conn.prepareStatement("Select * from tbl_name where id=?");
          DataInputStream dis=new DataInputStream(System.in);
          System.out.println("Enter id:- ");
          int id=Integer.parseInt(dis.readLine());
          preStatement.setInt(1, id);
          ResultSet result = preStatement.executeQuery();      
          while(result.next()){
            // fetch the data
          }
      }catch(Exception ex){ ... }
  </code></pre>
  
  <p>As both of these programs are capable of doing the same task.</p>
  
  <ul>
  <li>Why there is provision of two different Methods? Also looping seems to be easy if avoid repeatation is the answer.</li>
  <li>Can any one tell me which one is good to use ?</li>
  <li>what is the provision of each of them?</li>
  <li>What is the difference between them, and which one optimizes the code?</li>
  </ul>