In this post we will see the sample code to connect to Oracle Database using JDBC drivers in java.
For connecting to Oracle database we will need the following
1. Connection URL
The format is
jdbc:oracle:thin:@<SERVER_NAME>:<PORT>:<SID>
example:
jdbc:oracle:thin:@localhost:1525:kscodes
2. User Name
User Name of the database that we need to connect.
3. Password
Password of the database that we need to connect.
4. ojdbc
5. Oracle JDBC Driver Name
The driver used is oracle.jdbc.driver.OracleDriver
Steps: Connect to Oracle Database using JDBC
1. Register the JDBC Driver
Using the
Class.forName(...) we can register the Oracle JDBC driver.
2. Create Connection using DriverManager
Using the
DriverManager.getConnection(url,user,password) we can create the connection to the database.
Please remember to add the ojdbc
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package com.kscodes.sampleproject.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class OracleConnectExample { public static String DRIVER_CLASS_NAME = "oracle.jdbc.driver.OracleDriver"; public static String CONNECTION_URL = "jdbc:oracle:thin:@localhost:1525:kscodes"; public static String CONNECTION_USER = "kscodes"; public static String CONNECTION_PASSWORD = "kscodes"; public static void main(String[] args) { System.out.println("1. Register the JDBC Driver"); try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { System.out.println("Error while registering JDBC driver"); System.exit(0); } System.out.println("Oracle JDBC Driver Registered Successfully"); System.out.println("2. Create Connection using DriveManager"); Connection connection = null; try { connection = DriverManager.getConnection(CONNECTION_URL, CONNECTION_USER, CONNECTION_PASSWORD); } catch (SQLException e) { System.out.println("Failed to create Connection"); System.exit(0); } System.out .println("Connection created Successfully. Now use this connection to perform database operations....."); // Use this connection to fire queries and perform other database // operations } } |
Output
1 2 3 4 |
1. Register the JDBC Driver Oracle JDBC Driver Registered Successfully 2. Create Connection using DriveManager Connection created Successfully. Now use this connection to perform database operations..... |
Exceptions to be caught
1. ClassNotFoundException
2. SQLException