0
1.5kviews
Oracle Database Connection in Java
1 Answer
0
0views

How to Connect Java Application with Oracle Database

There are some steps you have to follow for java and oracle db connectivity.

1) Load Driver class

2) Create Connection Object

3) Set user name and password of oracle

4) Create Statement object

5) Execute query

6) Close connection object

Let's understand by an example

First, create table in oracle db by using below command

create table student(rollno number(10), name varchar2(40));

In the below program system is the default user name of oracle db and mca is a password of oracle db.

import java.sql.*;

class FetchAllRecords {
    public static void main(String args[]) {
        try {
            //Step 1, load driver class
            Class.forName("oracle.jdbc.driver.OracleDriver");

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

            //Step3, create statement
            Statement stm = con.creatStatement();

            //Step 4 , execute query
            ResultSet rs = stm.executeQuery("select * from student");

            while(rs.next()) {
                System.out.println(rs.getInt(1)+" " +rs.getString(2));
            }

            //Step 5, close connection object
            con.close();
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}
Please log in to add an answer.