Java - JDBC - Connecting with Oracle

The steps for connecting to an Oracle database using JDBC in Java:

  • Download and install the Oracle database and the Oracle JDBC driver.
  • Create a new Java project in your IDE.
  • Import the required JDBC packages into your Java project:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
  • Load the Oracle JDBC driver using the Class.forName() method:
Class.forName("oracle.jdbc.driver.OracleDriver");
  • Define the database URL, username, and password:
String url = "jdbc:oracle:thin:@localhost:1521:ORCL";
String username = "your-username";
String password = "your-password";
//Note: Replace your-username and your-password with your actual Oracle database username and password.

Establish a connection to the Oracle database using the DriverManager.getConnection() method:

Connection connection = DriverManager.getConnection(url, username, password);
  • Create a new statement object using the connection.createStatement() method:
Statement statement = connection.createStatement();
  • Execute SQL queries using the statement.executeUpdate() or statement.executeQuery() method:
String sql = "SELECT * FROM employees";
ResultSet resultSet = statement.executeQuery(sql);
  • Process the results of the SQL queries using the ResultSet object.
  • Close the ResultSet, Statement, and Connection objects:
resultSet.close();
statement.close();
connection.close();

Note: It is recommended to use a try-with-resources statement to automatically close the ResultSet, Statement, and Connection objects to avoid resource leaks.

These are the basic steps for connecting to an Oracle database using JDBC in Java.