Connect Oracle Database via JDBC: Step-by-Step

To connect to an Oracle database, you can use the JDBC driver provided by Oracle. Here are the steps to connect to an Oracle database:

  1. Download and install the Oracle JDBC driver: Begin by downloading the JDBC driver suitable for your Oracle database version from the official Oracle website and adding it to your project.
  2. Import the JDBC package in your code: Import the java.sql and oracle.jdbc.driver package in your Java code.
  3. Load the Oracle JDBC driver: Use the Class.forName() method in your code to load the Oracle JDBC driver.
  4. Establishing a database connection: To create a connection with an Oracle database, the DriverManager.getConnection() method is used, requiring the connection string, username, and password to be provided.
  5. Execute SQL query or update: Use a Connection object to create a Statement or PreparedStatement object, then execute your SQL query or update operation.
  6. Processing query results: If you are performing a query operation, you can retrieve the query results using the ResultSet object.
  7. Close connection: After using the database connection, it is important to close it to release resources.

Below is an example code for connecting to an Oracle database:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class OracleConnection {

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;

        try {
            // 加载Oracle JDBC驱动程序
            Class.forName("oracle.jdbc.driver.OracleDriver");

            // 创建数据库连接
            connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "username", "password");

            // 创建Statement对象
            statement = connection.createStatement();

            // 执行查询操作
            ResultSet resultSet = statement.executeQuery("SELECT * FROM employees");

            // 处理查询结果
            while (resultSet.next()) {
                System.out.println(resultSet.getString("employee_name"));
            }

        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

In the code above, we begin by loading the Oracle JDBC driver, then create a connection to the Oracle database and perform a simple query operation. Finally, we close the connection in the finally block to release resources. You can modify the code as needed to perform other operations.

bannerAds