To access Oracle from Java, follow these steps:
- Import Oracle JDBC Driver: Ensure you have the Oracle JDBC driver (e.g., ojdbc8.jar) in your classpath.
- Establish a Database Connection: Use the
DriverManager.getConnection
method with the Oracle database URL, username, and password. - Create Statement: Create a
Statement
orPreparedStatement
to execute SQL queries. - Execute Queries: Use the
executeQuery
orexecuteUpdate
methods to interact with the database. - Process Results: Retrieve the results using a
ResultSet
. - Close Resources: Always close the
Connection
,Statement
, andResultSet
to avoid resource leaks.
Sample Code:
import java.sql.*;
public class OracleAccess {
public static void main(String[] args) {
try {
Class.forName(\"oracle.jdbc.driver.OracleDriver\");
Connection conn = DriverManager.getConnection(
\"jdbc:oracle:thin:@localhost:1521:orcl\", \"username\", \"password\");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(\"SELECT * FROM employees\");
while (rs.next()) {
System.out.println(rs.getString(\"name\"));
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Ensure you replace the database URL and credentials with your actual information.