Share on Google+Share on Google+

Connection to database table in Oracle with Example

Advertisement
In this Section, we will discuss about connecting Java frontend with OracleDatabase.

Connection to database table in Oracle with Example

In this Section, we will discuss about connecting Java frontend with OracleDatabase.

Step1: First, Download the oracle driver and install or copy it in your system , if you are using "jdk" kit ,then copy it to "jdk1.6.0_18\jre\lib\ext" .

Step2:Create your program, And include Class.forName(oracle.jdbc.driver.OracleDriver) in your program to register it with "jdk". Also url path of your database must be correct.

Step3: Compile and Run your Program.

Connectoracle.java

import java.sql.*;
public class connectoracle {

  public static void main(String[] args) throws Exception {
    try{
    String driver = "oracle.jdbc.driver.OracleDriver"; 
    
  String url = "jdbc:oracle:thin:@127.0.0.1:1521:mydatabase";
    
  String username = "root";
    String password = "root";
    
    Class.forName(driver);
    Connection conn = DriverManager.getConnection(url, username, password);
   
  System.out.println("Connected");
    Statement st = conn.createStatement();
    
  ResultSet rs = st.executeQuery("SELECT * FROM employee");
    ResultSetMetaData rsmd = rs.getMetaData();
    int NumOfCol=rsmd.getColumnCount();
    System.out.println("Number of Columns="+NumOfCol);
   
  st.close();
    conn.close();
  }catch(SQLException ex) {
     for(Throwable e : ex ) {
        System.out.println("Error occurred: " + e);
     }
    } 
  }
}

OUTPUT

C:\Documents and Settings\admin\Desktop\ankit_jdbc>java Connectoracle
Connected
Number of Columns=2

Download this Code

Advertisements

Posted on: June 9, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.