Monday, November 19, 2012

Java Database Connectivity(JDBC) using Oracle 10g XE


Step 1: Install Oracle on Your PC
and Give classpath for Oracle Jar Files
GoTo Computer->System Properties->Advanced->Environmental Variables
User Variables->New
Variable name: classpath
Variable value: .;C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;

Step 2: Create Login table in Oracle Database 
Goto Run Sql Command Line
And write following commands
a) Connect to HR schema
b) Create Login Table with three columns Id,Username and Password

Step 3:
Here We are using Thin Driver, 1521 is port no. and XE stand for Oracle Express edition
First HR is Username and Second HR is Password of HR Schema. Our Login Table Exists in HR Schema.

 Source Code OracData.java
 import java.sql.*;  
 public class OracData  
 { public static void main(String[] args)  
   {  
      try  
      {Class.forName("oracle.jdbc.driver.OracleDriver");  
      Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");  
      Statement st=con.createStatement(); 
 
      /*Select Query and Display Data  
      ResultSet rs=st.executeQuery("select * from login");  
      While(rs.next())  
      {System.out.println(rs.getInt(1));  
      System.out.println(rs.getString(2));  
      System.out.println(rs.getString(3));  
      }*/  

      /*Updation by deletion  
      int i=st.executeUpdate("delete from login where id="+1);  
      System.out.println(i+" Record(s) Deleted successfully");*/  

      /*Updation by Insertion*/  
      String sql="insert into login values("+1+",'Himanshu','him123')";  
      int j=st.executeUpdate(sql);  
      System.out.println(j+" Record(s) Inserted successfully");  
      con.close();  
      }  
      catch(Exception e)  
      {  
      System.out.println(e);  
      }  
   }  
 }  

You can also use following command to insert data in place of above insert command
 /*Updation by Insertion using PreparedStatement  
 PreparedStatement statement=connection.prepareStatement("insert into login values(?,?,?)");  
 connection.setAutoCommit(true);  
 statement.setInt(1,1);  
 statement.setString(2, "Himanshu");  
 statement.setString(3, "him123");  
       int i=statement.executeUpdate();  
       if(i!=0)  
       out.println(i+" Record(s) inserted Successfully"); */  
  
Step 4: Execute code
Output: for Inserting Data

2 comments:

Narendra Rathore said...

I HAVE GOT CLASS NOT FOUND EXCEPTION HELP ME .
java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver,,,,SOLVE ME OUT THIS PROBLEM

Himanshu Bhasin said...

try Class.forName(oracle.jdbc.OracleDriver)
or try
Class.forName(oracle.jdbc.driver.OracleDriver)

Popular Posts