JDBC Connectivity with Oracle
Establishing a connection between a Java application and an Oracle Database using JDBC requires:
- Oracle JDBC Driver (ojdbc8.jar or ojdbc11.jar)
- Oracle Database installed (locally or on server)
- Valid username and password
- Correct connection string
Steps for Setup
Download Oracle JDBC Driver
- Retrieve ojdbc8.jar or ojdbc11.jar from Oracle's official website.
- Integrate the Oracle JDBC Driver into your project's classpath using your IDE or build tools such as Maven and Gradle.
Oracle JDBC Connection URL Format
jdbc:oracle:thin:@host:port:SID
jdbc:oracle:thin:@//host:port/service_name
Example
String url = "jdbc:oracle:thin:@localhost:1521:xe"; // SID-based String url = "jdbc:oracle:thin:@//localhost:1521/orclpdb"; // Service-name-based
Maven Dependency (if using Maven)
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>19.3.0.0</version>
</dependency>
Example
import java.sql.*;
public class OracleJDBCExample {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Step 1: Load the Oracle JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// Step 2: Establish the connection
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", // Your Oracle DB URL
"system", // Username
"oracle" // Password
);
// Step 3: Create a statement
stmt = con.createStatement();
// Step 4: Execute query
rs = stmt.executeQuery("SELECT * FROM employees");
// Step 5: Process result
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Step 6: Close all resources
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
| Error | Solution |
|---|---|
| ClassNotFoundException | Ensure ojdbc.jar is in your classpath |
| ORA-28000: the account is locked | Unlock the user via SQL*Plus or Admin tool |
| ORA-12514: TNS listener does not know | Use correct service name or SID in connection string |
| SQLRecoverableException: Closed Connection | Check if connection is closed before use |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com