Java and Oracle Introduction

Oracle is a database that can be used in conjunction with Java to create desktop, web and console based application. It can be used to store data, as well as configuration information. Java, together with SQL, can be used to query the data stored within an Oracle database, as well as insert, update and delete the data. In order for this to be possible, the Oracle JDBC Driver needs to be used.

Connecting to an Oracle Database

In order to access data within an Oracle database with Java, a connection to the database must first be established. Below is an example of how this can be achieved.

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

public class DemoOracle {

    public static void main(String[] args) {

        // Database and connection variables.
        String database = "jdbc:oracle:thin:@localhost:1521:XE";
        String username = "DemoUN";
        String password = "DemoPW";
        Connection connect = null;

        try {

            // Connect to database.
            connect = DriverManager.getConnection(
                    database, username, password);

            // Message confirming successful database connection.
            System.out.println("Database connection successful.");

        } catch (SQLException e) {

            // Message confirming unsuccessful database connection.
            System.out.println("Database connection unsuccessful.");

            // Stop program execution.




In this example, a ‘try-catch’ block is used to catch any exceptions that may arise in connecting to the database, which, in this case, is running on the same machine, or ‘localhost’, as the program. A ‘try-catch’ block can be used to handle any exceptions in a user friendly manner. The ‘System.exit(0)’ statement, after the confirmation of an unsuccessful database connection, stops execution of the program completely, so no further statements are executed.

It should be noted that it isn’t necessary to have the database information in separate variables before using it in the database connection. It much depends on personal preference and whether the variables are going to be re-used elsewhere in the program. The database connection variable can be re-written as follows.

// Connect to database.
connect = DriverManager.getConnection(
        "DemoUN", "DemoPW");