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.
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.
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.
|
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 |
1. | In JDeveloper, select File | New. The New Gallery displays.
|
2. |
In the Categories pane accept the default General, and from the Items pane, the default Application Workspace. Click OK.
|
3. | In the Create Application Workspace dialog, type HRAdmin. Ensure that the Application Template dropdown is set to No Template [All Technologies]. 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. 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.
|
1. | Select the project name in the Navigator, and go to Tools | Project Properties. The Project Properties dialog opens.
|
2. | Expand the Profiles node if it is not already expanded. Under the Development node, find and select Libraries. 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. Click OK.
|
1. | Select your project in the Navigator. Right-click and select New... from the short-cut menu.
|
2. | In the New Gallery, retain General as the default category, and select Java Class from the Items pane. 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. Click OK to display the code for the new class in the Code Editor.
|
You need to import the following packages to be able to use the JDBC classes:
java.sql.*
java.sql.SQLException.*
oracle.jdbc.driver.*
1. | In the Code Editor, on a new line under the generated package statement, start to type the following statement: import java.sql.*; 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.
|
3 . | Type the other two import statements as follows, using the Code Insight feature if you wish. import java.sql.SQLException.*;
|
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.
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.
|
2. | Type the values for the new department in the Program Arguments field, as follows: 280 Facilities_Management 1700 Bissot Click OK.
|
3. | In the Code Editor, add the following code to your public static void main statement: throws Exception 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];
|
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();
|
6. | Add a trace message to display the parameters being used in the run: System.out.println("using:
"
|
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.
|
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;
|
2. | Create a method called initialize to hold the connection code. public void initialize()
throws Exception
|
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(
|
4 . | To connect to the database, add the connect statement as follows: conn =
DriverManager.getConnection 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.
|
5 . | To disable autocommit for this connection, add the following statement: conn.setAutoCommit (false);
|
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");
|
7 . | In the code for the main method, invoke the initialize method, as follows: hRUpdates.initialize();
|
8 . | Run your program. The message "I am connected" displays in the Log window at the bottom of the screen.
|
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;
|
2. | Create a method called listEmp to hold the employee query code. public int listEmp(String
lastName) throws Exception
|
3. | In the listEmp method, create a statement object on a new line in the Code Editor, after the opening brace "{": stmt = conn.createStatement ();
|
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 + "'"); 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. int count = 0; 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:
|
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);
|
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.
|
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; 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
|
3 . | Now add the insert code with some exception
handling. try 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);
|
5 . | Check that the inserted values are correct. public void listDept(String
deptId) throws Exception
|
6. | Invoke the method from main. hRUpdates.listDept(deptId);
|
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
|
2. | Create the update code using the prepared statement object as you did for the department insert. pstmt = conn.prepareStatement( 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);
|
4. | Query the Employees table for the designated manager to
see the result of the update.
|
5. | Close the prepared statement, statement and connection objects. Create a method called terminate to hold the closing code. public void terminate()
throws Exception
|
6. | Invoke the terminate method from main: hRUpdates.terminate();
|
7. | Run the program to see the results of both the department insert and the employee update in the Log window.
|
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. |
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