Establishing
connection to Oracle through Java
The oracle JDBC in Java is an API that
enables users to access Oracle Database
from Java.
Steps to be followed to get Connection
1 Import the predefined
classes.
import java.sql.*;
2
Load the drivers that acts
as an interface from Java to Oracle.
Class.forName("oracle.jdbc.driver.OracleDriver");
3
Get connected to the database with your user
id and password
String user,pass,url;(store
user id in user and password in pass
url="jdbc:oracle:thin:@oracle.cs.uky.edu:1521:orcl";
Connection conn=DriverManager.getConnection(url,user,pass);
4
Interacting with the database from JDBC
Interaction is
achieved with the help of object of class Statement
Statement stmt=conn.createStatement();
Execution of query statement
stmt.executeUpdate(any
stmt);
Example : stmt.executeUpdate(“DROP
TABLE EMPLOYEE”);
Execution of non-query statement
stmt.executeQuery(query
stmt);
Example :
stmt.executeQuery(“SELECT
* FROM EMPLOYEE”);
End
of statement
stmt.close();
5
Disconnecting from database
conn.close();
Note:
1
All statements
mentioned above throws some exceptions so use TRY and CATCH
blocks.
2
Java is case
sensitive so Caps are to be used wherever shown.
3 Any names can be used for
the variables like conn, stmt, user, pass etc but it would
be good if they are relevant to the data it stores.