Sie sind auf Seite 1von 81

SQLJ Training

Company Confidential Copyright 2000 Deere & Company

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).

Company Confidential Copyright 2000 Deere & Company

SQLJ versus JDBC


SQLJ programs require fewer lines of code than JDBC programs. They are shorter, and hence easier to debug. SQLJ can perform syntactic and semantic checking on the code, using database connections at compile time.  SQLJ provides strong type-checking of query results and other return parameters, while JDBC values are passed to and from SQL without having been checked at compile time.
Company Confidential Copyright 2000 Deere & Company

Where Can You Use SQLJ?


 Applications  Applets  Servlets  JavaServer Pages  Enterprise JavaBeans
Company Confidential Copyright 2000 Deere & Company

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.

Company Confidential Copyright 2000 Deere & Company

Requirements for Using SQLJ


SQLJ translator  JDBC drivers  A version of the Sun Microsystems Java Development Kit (JDK)  Database

Company Confidential Copyright 2000 Deere & Company

Steps when using SQLJ


1. Import the Java packages that contain SQLJ and JDBC methods 2. Declare variables for sending data to or retrieving data from DB2 tables 3. Connect to a data source 4. Execute SQL statements 5. Handle SQL errors and warnings 6. Disconnect from the data source

Company Confidential Copyright 2000 Deere & Company

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.

Company Confidential Copyright 2000 Deere & Company

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.*;

Company Confidential Copyright 2000 Deere & Company

Basic SQLJ syntax


Any embedded SQLJ statement must conform to two simple rules: 1. The statement must be preceded by the syntax #sql. 2. The statement must end with a semi-colon ( ; ).

Company Confidential Copyright 2000 Deere & Company

You should also enclose the SQLJ statements within braces, and though it's optional, include the context in which the statement should be executed.

#sql [context] {DELETE FROM EMP_ACT};

Company Confidential Copyright 2000 Deere & Company

Passing information from an application


To insert into the EMP_ACT table, use the following syntax:

void m (String empno, String projno, int actno) throws SQLException { #sql [context] {INSERT INTO EMP_ACT (EMPNO, PROJNO, ACTNO) values (:empno, :projno, :actno)}; }

Company Confidential Copyright 2000 Deere & Company

Compiling SQLJ
Command: sqlj SqlJDemo.sqlj The sqlj translator creates a file named: SqlJDemo.java

Company Confidential Copyright 2000 Deere & Company

Statements that return a value


int result; #sql result = { VALUES update_product_price_func(1, 2) };

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.

Company Confidential Copyright 2000 Deere & Company

Host Variables and Expressions


Host variables allow SQLJ programs to exchange information between the embedded SQL statements and the rest of the Java program.  A host variable is any Java variable that is declared in the Java program.  Host variables may be referenced within a SQLJ statement, and SQLJ takes care of the details of moving data back and forth between the SQL and Java environments .  :[mode] host_variable
Company Confidential Copyright 2000 Deere & Company

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

Company Confidential Copyright 2000 Deere & Company

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 };

Company Confidential Copyright 2000 Deere & Company

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

Company Confidential Copyright 2000 Deere & Company

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 };

Company Confidential Copyright 2000 Deere & Company

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 };

Company Confidential Copyright 2000 Deere & Company

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.

Company Confidential Copyright 2000 Deere & Company

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 Database Null Values


Unfortunately, the Java numeric, logical, and bit types (int, float, boolean, and byte, for example) can't retrieve nulls from the database.  So what do you do if a column you want to select using a SQLJ statement may contain a null?  You must use the Java wrapper classes. A wrapper class is a Java class that allows you to define a wrapper variable, which can then be used to retrieve database nulls.
Company Confidential Copyright 2000 Deere & Company

Handling Database Null Values


// set the price to null #sql { UPDATE products SET price = NULL WHERE id = 1 }; // retrieve the null price into price_var #sql { SELECT price INTO :price_var FROM products WHERE id = 1 };

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.

Company Confidential Copyright 2000 Deere & Company

SQLException
try { #sql { DELETE FROM customers }; } catch (SQLException exception) { System.out.println("SQLException " + exception); }

Company Confidential Copyright 2000 Deere & Company

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

Company Confidential Copyright 2000 Deere & Company

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

Queries That Return Multiple Rows


The SELECT statement is used to retrieve rows from a database source such as a table or a view. There are two cases to consider: a SELECT that returns one row, and a SELECT that returns multiple rows. For the single row case, you can use the SELECT INTO statement described earlier in this chapter. For the case involving multiple rows, you must use a SQLJ iterator.
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.

Company Confidential Copyright 2000 Deere & Company

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.

You do not specify column names

Company Confidential Copyright 2000 Deere & Company

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 ...]);

Company Confidential Copyright 2000 Deere & Company

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

Declare the iterator class


#sql private static iterator ProductIteratorNamedClass ( int id, double price, String name, String description );

Company Confidential Copyright 2000 Deere & Company

Declare an iterator object from the iterator class


Java statement declares an iterator object named product_iterator from ProductIteratorNamedClass: ProductIteratorNamedClass product_iterator; The product_iterator object is now ready to be populated with the results of a SQL SELECT statement.

Company Confidential Copyright 2000 Deere & Company

Populate the iterator object using a SELECT statement


#sql product_iterator = { SELECT id, name, description, price FROM products WHERE id <= 5 };

Company Confidential Copyright 2000 Deere & Company

Read the rows from the iterator object


while (product_iterator.next( )) { // print the contents of the iterator row System.out.println("id = " + product_iterator.id( )); System.out.println("name = " + product_iterator.name( )); System.out.println("description = " + product_iterator.description( )); System.out.println("price = " + product_iterator.price( )); } // end of while loop
Company Confidential Copyright 2000 Deere & Company

Close the iterator object


Once processing of an iterator is complete, the iterator must be closed using the close( ) method.  product_iterator.close( );

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.

Company Confidential Copyright 2000 Deere & Company

Scrollable Iterators
#sql private static iterator NamedScrollableIterClass implements sqlj.runtime.Scrollable ( int id, String name ); NamedScrollableIterClass my_scrollable_named_iter;

Company Confidential Copyright 2000 Deere & Company

Scrollable positional iterators


#sql private static iterator PosScrollableIterClass implements sqlj.runtime.Scrollable ( int, String ); PosScrollableIterClass my_scrollable_pos_iter;

Company Confidential Copyright 2000 Deere & Company

Scrollable positional iterators


FETCH PREVIOUS or FETCH PRIOR
 Accesses the previous row.

 FETCH FIRST
 Accesses the first row.

 FETCH LAST
 Accesses the last row.

 FETCH ABSOLUTE :(row_number)


 Accesses the row specified by row_number. The parameter row_number can be any expression that evaluates to a Java int value.

 FETCH RELATIVE :(relative_row_number)


 Positions the iterator a specified number of rows forward or backward from the current row.

Company Confidential Copyright 2000 Deere & Company

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 { CALL update_product_price(1, .9) };


Company Confidential Copyright 2000 Deere & Company

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

Company Confidential Copyright 2000 Deere & Company

SQL Functions
int result; #sql result = { VALUES(update_product_price_func(1, 2)) }; Or #sql result = { VALUES update_product_price_func(1, 2) };

Company Confidential Copyright 2000 Deere & Company

The SET Statement


The SET statement is used to assign a value to a host expression. The syntax for a SQLJ executable statement that uses the SET statement is:  #sql { SET :host_expression = expression }; The syntax elements are as follows: host_expression
 Specifies the host expression. This has a default mode of OUT and may not be set to IN or INOUT (doing so will result in a translation time error).

 expression
 Specifies any valid SQL statement that returns a value that can be assigned to the host expression,
Company Confidential Copyright 2000 Deere & Company

The SET Statement


int result_sum = 0; #sql { SET :result_sum = update_product_price_func(1, .9) + update_product_price_func(2, .8) };

Company Confidential Copyright 2000 Deere & Company

The SET Statement


Date system_date = null;  #sqlj { SET :system_date = sysdate };

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

Defining Object Types




CREATE TYPE t_address AS OBJECT ( street VARCHAR2(15), city VARCHAR2(15), state CHAR(2), zip VARCHAR2(9) );

Company Confidential Copyright 2000 Deere & Company

Defining Object Types


CREATE TYPE t_customer AS OBJECT ( id NUMBER, first_name VARCHAR2(10), last_name VARCHAR2(10), dob DATE, phone VARCHAR2(15), address t_address, -- the function get_age( ) returns the age of the customer in years MEMBER FUNCTION get_age RETURN INTEGER );
Company Confidential Copyright 2000 Deere & Company

Defining Object Types


CREATE TYPE BODY t_customer AS -- the function get_age( ) returns the age of the customer in years MEMBER FUNCTION get_age RETURN INTEGER IS age INTEGER; BEGIN -- calculate the age in years SELECT ROUND(((sysdate - dob) / 365), 0) INTO age FROM dual; RETURN age; END; END;
Company Confidential Copyright 2000 Deere & Company

Object Columns and Object Tables


You can use object types to define columns in a table. Such columns are known as object columns because they contain objects rather than scalar values. You can also define tables so that each row in the table represents an instance of an object. Such tables are known as object tables.

Company Confidential Copyright 2000 Deere & Company

Object Columns
An object column is a column in a table that is defined using an object type CREATE TABLE customers ( customert_customer );

Company Confidential Copyright 2000 Deere & Company

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.

Company Confidential Copyright 2000 Deere & Company

Adding Objects to Tables


When adding a new row object or column object to a table, you must place the values for the object in a constructor for the object type. INSERT INTO customers (customer) VALUES ( t_customer(1, 'Y', 'P', '03-FEB-1978', '1234455', t_address('1 ABC', 'EFG', 'HI', '12345') ) );
Company Confidential Copyright 2000 Deere & Company

Retrieving Objects
When referencing an individual attribute in an object column, you must use an alias for the table in your SELECT statement.

SELECT c.customer FROM customers c WHERE c.customer.id = 1;

Company Confidential Copyright 2000 Deere & Company

Invoking Object Methods


SELECT c.customer.get_age( ) FROM customers c WHERE c.customer.id = 1; SELECT c.get_age( ) FROM customers2 c WHERE c.id = 1;

Company Confidential Copyright 2000 Deere & Company

Modifying Objects
You can modify an attribute of an object using an UPDATE statement.

UPDATE customers c SET c.customer.first_name = 'Yashodip' WHERE c.customer.id = 1;


Company Confidential Copyright 2000 Deere & Company

Accessing Database Objects Using SQLJ


Adding Objects There are two types of database objects: column objects and row objects

Company Confidential Copyright 2000 Deere & Company

Adding a column object


You can add a column object to a table using one of two methods: Use the object type constructor to set the object attributes in an INSERT statement. Use a host object in an INSERT statement. This method involves three steps:
 Create a host object using the appropriate custom class.  Set the host object attributes using the set mutator methods.  Use the host object in an INSERT statement.
Company Confidential Copyright 2000 Deere & Company

Adding a column object


#sql { INSERT INTO customers VALUES ( t_customer(1, 'Y', 'P', '03-FEB-1978', '1234455', t_address('1 ABC', 'EFG', 'HI', '12345') ) };

Company Confidential Copyright 2000 Deere & Company

Adding a row object


Adding a row object may be performed by setting the object attributes directly in an INSERT statement, just as you would set the columns for a non-object table.

Company Confidential Copyright 2000 Deere & Company

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

Declaring a host object


First, you need to declare a host object to store the column or row object to be retrieved. TCustomer customer; Once you have your host object, you can use a SELECT INTO statement to retrieve a columnor row object into that host object. The syntax of that SELECT INTO statement depends on whether you are retrieving a column object or a row object.

Company Confidential Copyright 2000 Deere & Company

Retrieving a column object


#sql { SELECT c.customer INTO :customer FROM customers c WHERE c.customer.id = 1 };
Company Confidential Copyright 2000 Deere & Company

Retrieving a row object


#sql { SELECT id, first_name, last_name, dob, address INTO :id, :first_name, :last_name, :dob, :address FROM customers2 WHERE id = 1 };
Company Confidential Copyright 2000 Deere & Company

Referencing object attributes


Once you've retrieved an object, you can access its attributes using the get accessor methods. System.out.println("id = " + customer.getId( )); System.out.println("first_name = " + customer.getFirstName( )); System.out.println("last_name = " + customer.getLastName( ));
Company Confidential Copyright 2000 Deere & Company

Modifying Object Attributes


You can modify the attributes of a column object or a row object using one of two possible methods: Modify the attributes directly in an UPDATE statement. Modify the attributes through a host object, and write this host object back into the database with an UPDATE statement.

Company Confidential Copyright 2000 Deere & Company

Modifying attributes directly using an UPDATE statement


#sql { UPDATE customers c SET c.customer.first_name = :first_name WHERE c.customer.id = 1 };

Company Confidential Copyright 2000 Deere & Company

Modifying attributes through a host object


Declare a host object using the custom class. Retrieve the original database object into the host object. Modify the attributes in the host object using the set mutator methods. Use the host object in an UPDATE statement to modify the original database object.
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.

Company Confidential Copyright 2000 Deere & Company

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.

Company Confidential Copyright 2000 Deere & Company

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') );

Company Confidential Copyright 2000 Deere & Company

Retrieving the Contents of a VARRAY


SELECT * FROM customers3 WHERE id = 1;

Company Confidential Copyright 2000 Deere & Company

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/

Company Confidential Copyright 2000 Deere & Company

Thank You

Company Confidential Copyright 2000 Deere & Company

Das könnte Ihnen auch gefallen