Beruflich Dokumente
Kultur Dokumente
SQLJ
SQLJ is a set of programming extensions that allow a programmer using the Java programming language to embed statements that provide SQL (Structured Query Language) database requests.
The two standard methods for accessing relational data from a Java program are SQLJ and Java Database Connectivity (JDBC).
SQLJ Components
SQLJ consists of two components: the translator and the runtime libraries. The translator reads a Java source file containing embedded SQL statements, which are then translated into calls to the SQLJ runtime libraries. These calls perform the actual database operations. SQLJ is an ISO and ANSI standard that was developed by many large corporations including Oracle, Sun, Microsystems, IBM, Compaq, Informix, and Sybase.
SQLJ Programs
A SQLJ program, like any other Java program, is divided up into blocks, and a SQLJ statement may appear anywhere that a normal Java statement may appear. All SQLJ statements begin with the language token #sql to differentiate those statements from other Java program statements.
Basics of SQLJ
To use SQLJ in a Java program to access DB2, you need to take a few steps before you begin coding. Include the following files either in a directory with your applications or in your CLASSPATH.
db2jcc.jar, which provides a JDBC driver (Type 4) sqlj.zip, which provides the SQLJ translator class files Location: SQLLIB/java
Company Confidential Copyright 2000 Deere & Company
import statements
import java.sql.*; import sqlj.runtime.*; import sqlj.runtime.ref.*;
You should also enclose the SQLJ statements within braces, and though it's optional, include the context in which the statement should be executed.
void m (String empno, String projno, int actno) throws SQLException { #sql [context] {INSERT INTO EMP_ACT (EMPNO, PROJNO, ACTNO) values (:empno, :projno, :actno)}; }
Compiling SQLJ
Command: sqlj SqlJDemo.sqlj The sqlj translator creates a file named: SqlJDemo.java
If an embedded SQL statement does return a result, you need a way to specify where that result should be placed. SQLJ syntax accommodates this need.
Host Variables
:[mode] host_variable
mode (optional)
Specifies the mode of the host expression and may be set to one of the following:
IN
The SQLJ statement may only read the value stored in the host variable (the value may not be changed).
OUT
The SQLJ statement should write a new value to the host variable.
INOUT
The SQLJ statement may both read and write the value of the host variable host_variable
The name of a Java variable in the program
Single-Row Queries
// declare host variables
int id = 2; String first_name = null; String last_name = null; java.sql.Date dob = null; String phone = null;
// perform SELECT to get the customer details for the customer #2 // from the customers table
#sql { SELECT first_name, last_name, dob, phone INTO :first_name, :last_name, :dob, :phone FROM customers WHERE id = :id };
Updating Rows
The SQL UPDATE statement is used to modify rows in a table. When an UPDATE statement is used in a SQLJ executable statement, host expressions can appear in the SET and WHERE clauses
Updating Rows
int new_quantity = 10; int cust_id = 2; int prod_id = 3; #sql { UPDATE purchases SET quantity = :new_quantity WHERE purchased_by = :cust_id AND product_id = :prod_id };
Deleting Rows
The SQL DELETE statement is used to remove rows from a table. When a DELETE statement is used in a SQLJ executable statement, host expressions can appear in the WHERE clause. #sql { DELETE FROM customers WHERE id = :cust_id };
Inserting Rows
The SQL INSERT statement is used to add rows to a table. When an INSERT statement is used in a SQLJ executable statement, host expressions can appear in the VALUES clause.
Inserting Rows
int id = 13; int type_id = 1; String name = "Life Story"; String description = "The Life and Times "; double price = 199.95; #sql { INSERT INTO products (id, type_id, name, description, price) VALUES(:id, :type_id, :name, :description, :price) };
Company Confidential Copyright 2000 Deere & Company
Inserting Rows
int id = 14; double new_price = 10.95; int prod_id = 4; #sql { INSERT INTO products SELECT :id, type_id, name, description, :new_price FROM products WHERE id = :prod_id };
Company Confidential Copyright 2000 Deere & Company
Handling Exceptions
SQLJ executable statements must be contained in a try/catch statement. The try block contains the SQLJ statements that may cause a java.sql.SQLException, and the catch block should contain the statements to be executed when a java.sql.SQLException is raised.
SQLException
try { #sql { DELETE FROM customers }; } catch (SQLException exception) { System.out.println("SQLException " + exception); }
java.sql.SQLNullException
Thrown when a database null value is selected into a Java primitive type. The try/catch statement in this example contains handlers for SQLNullException and SQLException. Notice that SQLNullException is placed before SQLException
Transactions
#sql { COMMIT [WORK] }; #sql { ROLLBACK [WORK] }; The syntax elements are as follows: COMMIT
Commits a transaction, making the changes permanent.
ROLLBACK
Rolls back a transaction, returning the database to the state it was in when the transaction first began. The effects of all SQL statements issued during the transaction will be erased.
WORK
An optional word that is part of the supported SQL syntax.
Company Confidential Copyright 2000 Deere & Company
Transactions
#sql { INSERT INTO customers (id, first_name, last_name, dob, phone) VALUES ('7', Girish', Verma', '03-FEB-1978', '123456') }; #sql { ROLLBACK };
Company Confidential Copyright 2000 Deere & Company
SQLJ Iterators
An iterator is used to process multiple rows retrieved by a database query. From a conceptual point of view, a SQLJ iterator is similar to a PL/SQL cursor. There are five steps that you must perform to use an iterator to process rows returned by a SELECT statement: 1. Declare the iterator class. 2. Declare an iterator object from the iterator class. 3. Populate the iterator object using a SELECT statement. 4. Read the rows from the iterator object. 5. Close the iterator object.
SQLJ Iterators
There are two types of iterator classes: named
Both the Java variable type and the iterator column name used to store each column retrieved from the database must be specified in the iterator class.
positional
Only the types of the Java variables used to store the columns retrieved from the database are specified in the iterator class.
Named Iterators
When declaring a named iterator class, both the Java variable type and the host variable name used to store each column retrieved from the database must be specified. The syntax for declaring a named iterator class is as follows:
#sql [modifiers] iterator class_name [implements_clause] [with_clause] (java_type column_name [, java_type column_name ...]);
Named Iterators
modifiers The Java class modifiers: public, private, protected, and static. class_name Specifies the name that you want to give the iterator class. implements_clause Specifies the interfaces that the iterator class implements. This corresponds to the Java implements clause and is discussed later in this chapter. with_clause Specifies a list of constants to define and initialize. The with clause is discussed later in this chapter. java_type Specifies the Java type of the iterator column represented by column_name. column_name Specifies the name of the iterator column
Company Confidential Copyright 2000 Deere & Company
Scrollable Iterators
A scrollable iterator gives you the freedom to access the rows stored in the iterator in non-sequential order. In order for an iterator class to support scrollable functionality, it must implement the sqlj.runtime.Scrollable interface.
Scrollable Iterators
#sql private static iterator NamedScrollableIterClass implements sqlj.runtime.Scrollable ( int id, String name ); NamedScrollableIterClass my_scrollable_named_iter;
FETCH FIRST
Accesses the first row.
FETCH LAST
Accesses the last row.
SQL Procedures
You can invoke the procedure from a SQLJ program by using the CALL statement. #sql { CALL procedure_name([parameter_list])}; The syntax elements are as follows: procedure_name
Specifies the name of the PL/SQL stored procedure
parameter_list
Specifies a comma-delimited list of parameters to pass to the PL/SQL stored procedure
SQL Functions
Functions must return a value, you should use a Java variable to store the result. #sql host_variable = { VALUES ( function_name([ parameter_list])) }; The syntax elements are as follows: host_variable
Specifies the host variable to use in storing the value returned
function_name
Specifies the name of the function
parameter_list
Specifies a list of parameters to be passed to the function
SQL Functions
int result; #sql result = { VALUES(update_product_price_func(1, 2)) }; Or #sql result = { VALUES update_product_price_func(1, 2) };
expression
Specifies any valid SQL statement that returns a value that can be assigned to the host expression,
Company Confidential Copyright 2000 Deere & Company
Database Objects
A class is known as an object type, and it's from an object type that actual database objects are instantiated. In order to access database objects using SQLJ, you must create special custom classes. These custom classes mirror the database types on which the database objects are based, and are used to declare host objects in your SQLJ program. A host object is similar to a host variable. It resides locally in your Java program and may be used to access database objects.
Company Confidential Copyright 2000 Deere & Company
CREATE TYPE t_address AS OBJECT ( street VARCHAR2(15), city VARCHAR2(15), state CHAR(2), zip VARCHAR2(9) );
Object Columns
An object column is a column in a table that is defined using an object type CREATE TABLE customers ( customert_customer );
Object Tables
An object table is a table in which each row contains one object of a given object type. Such objects are known as row objects. You create an object table using the CREATE TABLE OF statement.
Retrieving Objects
When referencing an individual attribute in an object column, you must use an alias for the table in your SELECT statement.
Modifying Objects
You can modify an attribute of an object using an UPDATE statement.
Retrieving Objects
Retrieval of a column or row object from a table may be accomplished using the following steps:
Declare a host object using the custom class for the object type that you wish to retrieve. Using a SELECT INTO statement or an iterator, retrieve the column or row object into the host object. Read the host object's attributes using the get accessor methods.
Company Confidential Copyright 2000 Deere & Company
Collections
There are two types of collections. The first is known as a VARRAY, which enables a variable-length array to be stored within a table. The second is a nested table, which enables a table to be stored within another table. These collection types allow rows that make up the detail part of a relationship to be grouped with the master rows.
VARRAYs
A VARRAY is an ordered set of elements. The maximum number of elements in a VARRAY is set when the VARRAY is created. You create a VARRAY by first declaring a type, and then using that type to define a column in a table.
VARRAYs
CREATE TYPE t_address2 AS VARRAY(3) OF VARCHAR2(50); / CREATE TABLE customers3 ( id NUMBER, first_name VARCHAR2(10), last_name VARCHAR2(10), addresses t_address2 );
Company Confidential Copyright 2000 Deere & Company
INSERT INTO customers3 VALUES (1, G', V', t_address2('1 a, b, c, 12345', 602 Magarpatta city,as, pune, 54321') );
References
http://www.stanford.edu/dept/itss/docs/oracle/9i/java.920/a96655/toc.htm http://www.javaworld.com/javaworld/jw-05-1999/jw-05-sqlj_p.html http://www-128.ibm.com/developerworks/db2/library/techarticle/dm0412cline/
Thank You