How to connect java program with oracle 11g?

Member

by lew , in category: MySQL , 4 months ago

How to connect java program with oracle 11g?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 4 months ago

@lew 

To connect a Java program with Oracle 11g database, you can follow these steps:

  1. Download and install the Oracle JDBC driver for Oracle 11g. You can find the driver on the Oracle website.
  2. Add the Oracle JDBC driver to your Java project. This can be done by adding the JAR file to your project's build path.
  3. Import the required classes from the JDBC driver package in your Java program. This includes classes such as DriverManager, Connection, Statement, etc.
  4. Create a connection to the Oracle database using the DriverManager class. You will need to provide the database URL, username, and password in the getConnection() method.
  5. Write SQL queries to interact with the database. You can use the Statement or PreparedStatement class to execute queries and retrieve results.
  6. Close the connection to the database using the Connection class's close() method once you have finished executing your queries.


Here's an example code snippet that demonstrates connecting to an Oracle database and executing a simple query:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.sql.*;

public class OracleConnection {
    public static void main(String[] args) {
        String url = "jdbc:oracle:thin:@localhost:1521:YOUR_DATABASE_NAME";
        String user = "YOUR_USERNAME";
        String password = "YOUR_PASSWORD";

        try {
            // Establish a connection to the database
            Connection connection = DriverManager.getConnection(url, user, password);

            // Create a statement object
            Statement statement = connection.createStatement();

            // Execute a simple query
            ResultSet resultSet = statement.executeQuery("SELECT * FROM YOUR_TABLE");

            // Process the results
            while (resultSet.next()) {
                System.out.println(resultSet.getString("COLUMN_NAME"));
            }

            // Close the connection
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}


Make sure to replace "YOUR_DATABASE_NAME", "YOUR_USERNAME", "YOUR_PASSWORD", and "YOUR_TABLE" with your actual database details before running the program.