Performing SQL Queries Using JDeveloper and JDBC

This tutorial shows you how to use JDeveloper and JDBC to access an Oracle database to run SQL queries and manipulate data.

Topics

This lesson discusses the following:

 
Overview
Prerequisites
Setting up the environment  
Defining the parameters
Getting connected
Executing a query
Inserting a row into a table
Updating data in the database
Summary

This tutorial takes approximately 60 minutes to complete.
 

Move your mouse over this icon to show all screenshots. You can also move your mouse over each individual icon to see only the screenshot associated with it.

 
 

Overview

This tutorial shows you how to access and manipulate the data in an Oracle database, from a Java program, using JDeveloper. You run some simple SQL queries, you insert a row into a table, and you update a related table. Finally you requery the database to see the results of your work.

Back to Topic List

You are a Java developer, working on HR applications. A new department, Facilities Management, in location 1700, has just been created, headed up by Laura Bissot. You need to insert the Facilities Management information into the Departments table and update Laura Bissot's employee record with her new position.

Prerequisites

Back to Topic List

In order for this lesson to work successfully, you need to have performed the following:
 
1.
Install Oracle JDeveloper 10g.

 

2.
Install the Oracle sample schemas. This example uses the HR schema included in the Oracle database. Install the schema according to the instructions in Installing the Sample Schemas and
Establishing a Database Connection
.

 

Setting Up the Environment

Back to Topic List

Before you can start to use JDBC in JDeveloper, you must perform certain setup tasks. You first need a workspace and project in which to store your work, and then you add the JDBC libraries to the project. You also need to import the packages that enable you to use the JDBC classes. Follow these steps to set up your environment:
Create a new workspace and project  
Add the JDBC libraries to the project
Create a new Java class
Import the packages you need to be able to use the JDBC classes

 

Create a new workspace and project

Back to List

1.

In JDeveloper, select File | New. The New Gallery displays.

Move your mouse over this icon to see the image

 

2.

In the Categories pane accept the default General, and from the Items pane, the default Application Workspace.

Move your mouse over this icon to see the image

Click OK.

 

3.

In the Create Application Workspace dialog, type HRAdmin. Ensure that the Application Template dropdown is set to No Template [All Technologies].

Move your mouse over this icon to see the image

Note that the application template automatically provides you with a single project configured to allow easy access to all JDeveloper technologies.

 

4 .

The new workspace and project are displayed in the Applications Navigator. Select the workspace name, and choose File | Save All.

Move your mouse over this icon to see the image

Note that the font for the workspace and project names is no longer italicized. Italics indicate that a project or workspace has not yet been saved.

 


Add the JDBC libraries to the project

Back to List

1.

Select the project name in the Navigator, and go to Tools | Project Properties.

Move your mouse over this icon to see the image

The Project Properties dialog opens.

 

2.

Expand the Profiles node if it is not already expanded. Under the Development node, find and select Libraries.

Move your mouse over this icon to see the image

A list of the available libraries for the J2SE version is displayed.

 

3 .

Scroll through the list to find Oracle JDBC. Select it, and use the single right-pointing arrow to shuttle it into the Selected Libraries pane.

Move your mouse over this icon to see the image

Click OK.

 

 

Create a new Java class

Back to List

1.

Select your project in the Navigator. Right-click and select New... from the short-cut menu.

Move your mouse over this icon to see the image

 

2.

In the New Gallery, retain General as the default category, and select Java Class from the Items pane.

Move your mouse over this icon to see the image

Click OK.

 

3 .

In the Create Java Class dialog, type the name HRUpdates. Note the Optional Attributes box: leave the Public and Generate Default Constructor checkboxes checked, and in addition, check the Generate Main Method checkbox.

Move your mouse over this icon to see the image

Click OK to display the code for the new class in the Code Editor.

 

 

Import the packages you need to be able to use the Java classes

You need to import the following packages to be able to use the JDBC classes:

java.sql.*
java.sql.SQLException.*
oracle.jdbc.driver.*

Back to List

1.

In the Code Editor, on a new line under the generated package statement, start to type the following statement:

import java.sql.*;

Move your mouse over this icon to see the image

Note that the Code Insight feature of JDeveloper prompts you as you type by offering you a list of possible options to complete the statement.

 

2.

Double-click on an option in the list to add it to your statement.

Move your mouse over this icon to see the image

 

3 .

Type the other two import statements as follows, using the Code Insight feature if you wish.

import java.sql.SQLException.*;
import oracle.jdbc.driver.*;

Move your mouse over this icon to see the image

 

Defining the parameters

The application allows users to input values for a new department i.e the department Id, its name, and its location code, and to specify the name of the employee who is going to be the acting manager of the new department.
You need to list the values to be used at run time, in the Project Properties window in JDeveloper. You should also declare variables for these four arguments in your main method.

Back to Topic List

1.

Double-click the project name in the Navigator, to invoke the Project Properties dialog, and select Runner from the options displayed under Profiles | Development.

Move your mouse over this icon to see the image

 

 

2.

Type the values for the new department in the Program Arguments field, as follows: 280 Facilities_Management 1700 Bissot

Move your mouse over this icon to see the image

Click OK.

 

3.

In the Code Editor, add the following code to your public static void main statement:

throws Exception

Move your mouse over this icon to see the image

This removes the requirement to catch any exceptions thrown in this method. In general you should catch the exceptions thrown and handle them appropriately.

 

4.

Declare the variables and store the arguments, by creating a new line after the first brace "{" and typing the following statements:

String deptId = args[0];
String deptName = args[1];
String deptLocation = args[2];
String deptManager = args[3];

Move your mouse over this icon to see the image

 

5.

Note that an instance of the HRUpdates class is created for you as part of the main method. This is where all the methods of the class are to be defined. It appears as follows:

HRUpdates hRUpdates = new HRUpdates();

Move your mouse over this icon to see the image

 

6.

Add a trace message to display the parameters being used in the run:

System.out.println("using: "
+ " " + deptId
+ " " + deptName
+ " " + deptLocation
+ " " + deptManager
);

Move your mouse over this icon to see the image

 

7 .

To run your program, right-click in the Code Editor and choose Run from the context menu. The parameters specified in the Project Properties dialog are displayed in the Log window.

Move your mouse over this icon to see the image

 

 

Getting connected

Back to Topic List

In order to connect to the database, JDBC drivers must first register themselves with the driver manager. There are various ways of doing this, but this example uses the register.Driver() method of the java.sql.DriverManager class. You then call the getConnection() method to create the connection.
When you create a Connection object, it is in autocommit mode, meaning that each SQL statement is committed after it is executed. However you can disable autocommit, and group the statements into transactions, which must then be explicitly terminated by calling commit() or rollback(). This example shows you how to disable autocommit.

 
1.

Declare a connection instance in your HRUpdates class definition. To do this, create a new line after the first curly brace "{" below your class declaration, and type as follows:

Connection conn;

Move your mouse over this icon to see the image

 

2.

Create a method called initialize to hold the connection code.

public void initialize() throws Exception
{
}

Move your mouse over this icon to see the image

 

3 .

Register the driver by creating a new line after the first brace "{" and typing the following statement, using Code Insight if you wish:

DriverManager.registerDriver(
new oracle.jdbc.driver.OracleDriver());

Move your mouse over this icon to see the image

 

4 .

To connect to the database, add the connect statement as follows:

conn = DriverManager.getConnection
("jdbc:oracle:thin:@hostname:1521:dbname",
"hr","hr");

Replace hostname, JDBC port, and dbname with appropriate values for your environment, and use "hr" and "hr" as the username and password to connect to the HR schema. If you do not know the values for the hostname, JDBC port and dbname, check with your database administrator.

Move your mouse over this icon to see the image

 

5 .

To disable autocommit for this connection, add the following statement:

conn.setAutoCommit (false);

Move your mouse over this icon to see the image

 

6 .

Add the following line of code to check that you have managed to successfully connect to the database:

System.out.println("I am connected");

Move your mouse over this icon to see the image

 

7 .

In the code for the main method, invoke the initialize method, as follows:

hRUpdates.initialize();

Move your mouse over this icon to see the image

 

8 .

Run your program. The message "I am connected" displays in the Log window at the bottom of the screen.

Move your mouse over this icon to see the image

 

 

Executing a query

Back to Topic List

Once you have registered the driver and connected to the database, you are ready to run queries against the data. Before adding the new department to the Departments table, you need to confirm that the name of the employee assigned to manage it, is valid. In the example, this is done by attempting to list any employee with the same last name as that input as a parameter.

You create a JDBC statement object, and use the createStatement() method as the context for executing your SQL statement. For queries you use the executeQuery() method of the Statement interface. This method takes a SQL statement as input and returns a JDBC ResultSet object. The next() method is then used to iterate through the rows of the result set. The following steps guide you through the process of executing a query and outputting the results.

 

1.

Declare a statement instance in your HRUpdates class definition. To do this, create a new line below your connection declaration, and type in the following code:

Statement stmt;

Move your mouse over this icon to see the image

 

2.

Create a method called listEmp to hold the employee query code.

public int listEmp(String lastName) throws Exception
{
}

Move your mouse over this icon to see the image

 

3.

In the listEmp method, create a statement object on a new line in the Code Editor, after the opening brace "{":

stmt = conn.createStatement ();

Move your mouse over this icon to see the image

 

4.

Use the executeQuery() method to frame your SQL statement, and return a result set to check the uniqueness of the name that was passed as a program parameter. To do this, add the following code to the method:

ResultSet rset = stmt.executeQuery ("SELECT LAST_NAME, EMPLOYEE_ID, JOB_ID FROM EMPLOYEES where LAST_NAME = '" + lastName + "'");

Move your mouse over this icon to see the image

Note the single quote characters enclosing the lastName variable.

 

5.

List the values for the employee's name, department Id and job title of any rows retrieved by the query and count each row.
To loop through the rows of a result set, use the next() method. Zeroize a count field beforehand.

int count = 0;
while (rset.next ())
{
count++;
System.out.println(rset.getString(1) + " " + rset.getInt(2) + " " + rset.getString(3));
}

Move your mouse over this icon to see the image

Note that the rset.getXXX methods need the required column number of the result row as a parameter.

 

6 .

Return the count of rows retrieved to the calling code, as follows:

return count;

Move your mouse over this icon to see the image

 

7 .

In the code for the main method, invoke the listEmp method, and check that only one employee with that name, exists.

int empCount = hRUpdates.listEmp(deptManager);
if (empCount !=1 )
{
System.out.println ("ERROR: Employee " + deptManager +
" not valid");
return;

}

Move your mouse over this icon to see the image

 

8 .

Run the program. The Log window displays the name, employee id and job title that matches the name input as a program parameter. As there is only one row, the name is valid.

Move your mouse over this icon to see the image

 

 

 

Inserting a row into a table

Back to Topic List

Having checked that the nominated manager is a valid employee, you are ready to insert the new department into the table. There are four columns: Department_Id, Department_Name, Manager_Id (optional) and Location_Id. Because you disabled autocommit in a previous step, you must explicitly commit the Insert to the database. In addition, you add some exception-handling code to check for SQL errors. If it finds any, it reports the error and terminates the program. This checks that a department cannot be inserted twice.
Finally you confirm that the insert has taken place, by running a query against the Departments table.

 

1.

Declare a prepared statement instance in your HRUpdates class definition. To do this, create a new line below your statement declaration, as follows:

PreparedStatement pstmt;

Move your mouse over this icon to see the image

Note that because the insert command requires several value substitutions, it is preferable to use the PreparedStatement object instead of the string concatenation technique used in the earlier query.

 

2.

Create a method called insertDept to hold the insert code.

public int insertDept
(String deptId, String deptName, String deptLocation)
{
}

Move your mouse over this icon to see the image

 

3 .

Now add the insert code with some exception handling.
Enclose the insert and commit statements within a try block.Then add a catch block,that reports any errors, and terminates the program. The code for this is as follows:

try
{
pstmt = conn.prepareStatement(
"INSERT INTO DEPARTMENTS VALUES(?,?,NULL,?)");
pstmt.setInt(1, Integer.parseInt(deptId));
pstmt.setString(2, deptName);
pstmt.setInt(3, Integer.parseInt(deptLocation));
pstmt.executeUpdate();
conn.commit();
return 0; // return OK

}

catch (SQLException e)
{
System.out.println("Error on Insert" + e);

return 1; // return error
}

Move your mouse over this icon to see the image

Note that the pstmt.setXXX methods need the substitution value index as a parameter.

 

4.

In the code for the main method, invoke the insertDept method, and check for error return.

int result = hRUpdates.insertDept(deptId, deptName, deptLocation);
if (result != 0)
{
System.out.println("ERROR: Department " + deptId + " not valid");
return;
}
System.out.println("-Department added");

Move your mouse over this icon to see the image

 

5 .

Check that the inserted values are correct.
Create a method called listDept to query the inserted row. (This follows the same approach as the listEmployee method above).

public void listDept(String deptId) throws Exception
{
stmt = conn.createStatement ();
ResultSet rset = stmt.executeQuery ("SELECT * FROM DEPARTMENTS where DEPARTMENT_ID = "
+ deptId + " ");
while (rset.next ())
{
System.out.println( rset.getInt(1) + " " + rset.getString(2)
+ " " + rset.getInt(4));
}

}

Move your mouse over this icon to see the image

 

6.

Invoke the method from main.

hRUpdates.listDept(deptId);

 

Move your mouse over this icon to see the image

 

 

Updating Data in the Database

Back to Topic List

You now have a new department as specified by run parameters. The designated manager's record in the Employees table now needs to be updated to reflect her new department, and her new position, which initially defaults to AC_MGR (Acting Manager).

 

1.

Create a method called updateEmp to hold the update code.

public void updateEmp(String deptId, String lastName) throws Exception
{
}

Move your mouse over this icon to see the image

 

2.

Create the update code using the prepared statement object as you did for the department insert.

pstmt = conn.prepareStatement(
"UPDATE EMPLOYEES SET DEPARTMENT_ID= ? , JOB_ID= ? WHERE LAST_NAME= ?");
pstmt.setInt(1, Integer.parseInt(deptId));
pstmt.setString(2, "AC_MGR");
pstmt.setString(3, lastName);
pstmt.executeUpdate();
conn.commit();

Move your mouse over this icon to see the image

Note that this code should ideally contain some try....catch error handling as coded for the insert step

 

3.

Iinvoke the updateEmp method from main:.

hRUpdates.updateEmp(deptId, deptManager);

Move your mouse over this icon to see the image

 

 

4.

Query the Employees table for the designated manager to see the result of the update.
In main invoke the listEmp method created earlier, adding a message to show that this is after the insert and update:


hRUpdates.listEmp(deptManager);
System.out.println("Emp after update");

Move your mouse over this icon to see the image

 

5.

Close the prepared statement, statement and connection objects. Create a method called terminate to hold the closing code.

public void terminate() throws Exception
{
pstmt.close();
stmt.close();
conn.close();
}

Move your mouse over this icon to see the image

 

6.

Invoke the terminate method from main:

hRUpdates.terminate();

Move your mouse over this icon to see the image

 

7.

Run the program to see the results of both the department insert and the employee update in the Log window.

Move your mouse over this icon to see the image

 

8.

Confirm that the insertDepartment error-handling code is working by running the program again. It tries to insert the same row into the Departments table, but since the row now exists, the program terminates, outputting the 'Error on Insert' message, and the SQLException unique constraint violation.

Move your mouse over this icon to see the image

 

This tutorial showed you how you can use JDeveloper and JDBC to access an Oracle database from a Java application. You ran queries against tables, you inserted data into a table, and you updated a table.

 

Move your mouse over this icon to hide all screenshots