Saturday, 3 January 2015

JDBC Example to connect with Oracle Database

For connecting java application with the oracle database, you need to follow 5 steps to perform database connectivity. In this example we are  using Oracle10g as the database.

>1. Create a table with name employee in oracle database and insert some value to show our                    connection.

 create table employee(eid number(10), ename varchar2(40), salary number(20));

 >2. Insert some values.
 insert into employee (eid, ename, salary) values (111, 'Vishwa', 25000);
 insert into employee (eid, ename, salary) values (22, 'Alex', 30000);
 insert into employee (eid, ename, salary) values (333, 'Karan', 40000);

Example to Connect Java Application with Oracle Database.

In this example, system is the username and oracle is the password of the Oracle database.

import java.sql.*;
class OracleConnection
{
public static void main(String [] args) {

try{
 // loading  the driver class
 Class.forName("oracle.jdbc.driver.OracleDriver");

 // creating the connection object
 Connection con=DriverManager.getConnection(
 "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

 // creating the statement object
 Statement stmt=con.createStatement();

 // executing  query
 ResultSet rs=stmt.executeQuery("select * from employee");
 while( rs.next())
{
 System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
}

 // closing  the connection object
 con.close();
 }
 catch(Exception e)  {   System.out.println(e);  }
  }
 }

 Output: 
 111 Vishwa 25000
 222 Alex 30000
 333 Karan 40000

No comments:

Post a Comment