PreparedStatement example

Below program is an example of PreparedStatementExample. In this case also 10 rows will be inserted but the statement will be parsed once and it will be executed for 10 times. Almost all the business applications repeatedly execute the same statement with a different set of values. So it is always better to use prepared statement.
package com.ram.app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class PreparedStatementExample{
 public static void main(String[] args) throws Exception{
  Class.forName("oracle.jdbc.driver.OracleDriver");
  Connection conn = DriverManager.getConnection("dbc:oracle:thin:@localhost:1521:xe","hr","hr");
  
  PreparedStatement pstmt = conn.prepareStatement("insert into sample values(?)");
  for(int i=0; i<10; i++){
   pstmt.setInt(1, i);
   pstmt.executeUpdate();
  }
 }
}
Execute PreparedStatementExample.java file. Output is given below.

No comments:

Post a Comment