January 1, 2012

JDBC Prepared Statement Code Example

0) Complete the first 6 steps in the JDBC Code Example at the link here

1) Create a java class - JdbcPSExample.java - to the src folder of the Java Project / Application


package info.icontraining.jdbc;

import java.sql.*;

public class JdbcPSExample {

   public static void main(String[] args) throws SQLException, ClassNotFoundException {
  
      Class.forName("oracle.jdbc.OracleDriver");
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","system");
      PreparedStatement pstmt = conn.prepareStatement("insert into jdbcdemo values (?, ?, ?, ?)");
  
      pstmt.setString(1, "Dinesh");
      pstmt.setString(2, "PC");
      pstmt.setInt(3, 32);
  
      Date d = new Date(0);
      pstmt.setDate(4, d.valueOf("1978-9-28"));

      int rowsAffected = pstmt.executeUpdate();
      System.out.println(rowsAffected + " rows affected.");

      pstmt.setString(1, "Tanvi");
      pstmt.setString(2, "C");
      pstmt.setInt(3, 26);
      pstmt.setDate(4, d.valueOf("1984-10-30"));
  
      rowsAffected = pstmt.executeUpdate();
      System.out.println(rowsAffected + " rows affected.");

      pstmt.close();
      conn.close(); 
   }
}


3) Run the Example as a standalone Java Application