Database Connectivity with Oracle

Learn how to connect to Oracle database


Download Driver

Download oracle driver from Here. Extract files and copy jar file into jre/lib/ext/ directory or you can set classpath.

Connect with Database

In order to connect to oracle database you need to know user and password for database server.
Database url will be

jdbc:oracle:thin:@localhost:1521:xe

import java.sql.*;  
 public class dataConnect
  {
    public static void main(String arg[]) throws Exception
	 {
	  // Load the Driver
	  Class.forName("oracle.jdbc.driver.OracleDriver");
	  
	  // Create connection
	  // Specify user name and password of your database server
	  Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","root","root");	  
	  System.out.println("Connected to database");
	  Statement stmt=conn.createStatement();
	  ResultSet rs=stmt.executeQuery("select * from mydata");
	   while(rs.next())
	    {
		  System.out.println("id:"+rs.getInt("id"));
		  System.out.println("name:"+rs.getString("name"));
		}
		rs.close();
		stmt.close();
		conn.close();
	 
	 }
	 
  }

Execution

If you have copied downloaded jar file into jar/lib/ext directory then use following command for execution.

C:\Users\Jgyan\Desktop>java dataConnect

Otherwise specify classpath at execution time. [Let's assumen program and jar files both stored on desktop.]

C:\Users\Jgyan\Desktop>java -cp jdbc-oracle.jar;. dataConnect