Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Do Database Connectivity Using Java for Oracle Database?

Database Connectivity in Java for Oracle

Description for Database Connectivity Using Java for Oracle Database

  • Description: Database connectivity in Java for an Oracle database involves using the JDBC API to load the Oracle JDBC driver, and configure a connection URL with the database's hostname, port, and service name or SID. The DriverManager class establishes the connection, and SQL queries are executed via Statement or PreparedStatement objects. Proper error handling and connection closure are essential for efficient resource management.
Steps for Database Connectivity
  • STEP 1: Click the **Services** tab. Expand the **Drivers** node from the Database Explorer. Right-click the MySQL (Connector/J driver) and select **Connect Using**. The New Database Connection dialog box will be displayed.
  • Database Connection Dialog
  • STEP 2: In the **Basic Setting** tab, enter the Database's URL in the corresponding text field. The URL identifies the type and location of a database server. The format is `jdbc:mysql://hostname:port/database_name`. Enter your **User Name** and **Password**.
  • Enter Database URL
  • STEP 3: Click **OK** to accept the credentials. This displays a new **Connection** node in the Database Explorer under the Databases node. Click **OK** to accept the default schema. Right-click the **MySQL Database URL** in the Services window (Ctrl-5). Click **Connect**. This opens the New Database Connection dialog box.
  • Database Connection Confirmation
  • STEP 4: To list out the database details.
  • To list out the database details.
  • STEP 5: Output.
  • Output.
Sample Source Code
  • # OracleDBConnection.java
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    import javax.swing.JOptionPane;

    public class OracleDBConnection {
    public static void main(String[] args) {
    try {
    // Loading the Oracle JDBC driver
    Class.forName("oracle.jdbc.driver.OracleDriver");
    // Creating connection to the Oracle database
    Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "username", "password");
    Statement st = con.createStatement();
    // Create and execute an SQL query
    String sql = "SELECT * FROM employees";
    ResultSet rs = st.executeQuery(sql);
    while (rs.next()) {
    System.out.println("Employee ID: " + rs.getInt("emp_id") + ", Name: " + rs.getString("name"));
    }
    st.close();
    con.close();
    } catch (Exception ex) {
    System.err.print("Exception: ");
    System.err.println(ex.getMessage());
    }
    }
    }