How to configure a connection between Java and Oracle?

To establish a connection with an Oracle database in Java, you need to first download and install the JDBC driver that is suitable for your Oracle database version. Then, you can configure the connection by following these steps: 1. Import the necessary classes.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

Use the following code to establish a connection between a Java application and an Oracle database:

public class OracleConnection {

   public static void main(String[] args) {

      // 驱动程序名称和数据库URL

      String driver = "oracle.jdbc.driver.OracleDriver";

      String url = "jdbc:oracle:thin:@localhost:1521:ORCL"; // 根据您的实际数据库配置进行修改

      // 数据库凭据

      String username = "yourUsername";

      String password = "yourPassword";

      // 建立连接

      Connection conn = null;

      try {

         Class.forName(driver); // 加载驱动程序

         conn = DriverManager.getConnection(url, username, password); // 建立连接

         System.out.println("连接成功!");

      } catch (ClassNotFoundException e) {

         e.printStackTrace();

      } catch (SQLException e) {

         e.printStackTrace();

      } finally {

         if (conn != null) {

            try {

               conn.close(); // 关闭连接

            } catch (SQLException e) {

               e.printStackTrace();

            }

         }

      }

   }

}

Please modify the driver program name, database URL, username, and password according to the actual situation. This will allow you to establish a connection with an Oracle database using Java.

bannerAds