View
223
Download
1
Category
Preview:
Citation preview
11 © D. Wong 2003© D. Wong 2003
Java API for XML Processing (JAXP)Java API for XML Processing (JAXP) For processing XML data using applications written in For processing XML data using applications written in
Java Java JAXP APIs - javax.xml.parsers packageJAXP APIs - javax.xml.parsers package Leverages 2 parser standards :Leverages 2 parser standards :
SAX (Simple API for XML Parsing) SAX (Simple API for XML Parsing) parse the data as a stream of events, a serial-access parse the data as a stream of events, a serial-access
mechanism that does element-by-element processingmechanism that does element-by-element processing DOM (Document Object Model) (easier to use)DOM (Document Object Model) (easier to use)
build a tree structure of objects to represent the build a tree structure of objects to represent the datadata
org.w3c.dom org.w3c.dom Detail review of the enrollment example Detail review of the enrollment example (files posted (files posted
on the course web page as JAXP example)on the course web page as JAXP example) http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPIntro5.htmlhttp://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPIntro5.html
22 © D. Wong 2003© D. Wong 2003
Ch. 7 Constraints and TriggersCh. 7 Constraints and Triggers
Keys as constraintKeys as constraint
Foreign key constraints and referential integrityForeign key constraints and referential integrity
Constraints on attributesConstraints on attributes
Constraints on tuplesConstraints on tuples
AssertionsAssertions
TriggersTriggers
33 © D. Wong 2003© D. Wong 2003
Keys as ConstraintKeys as Constraint
One primary key per relationOne primary key per relation Declared in CREATE TABLEDeclared in CREATE TABLE 2 ways:2 ways:
1.1. List with attribute (when only 1 attribute in key) e.g. List with attribute (when only 1 attribute in key) e.g. snum char (5) PRIMARY KEYsnum char (5) PRIMARY KEY
2.2. Add to the list of items declared in the schema. E.g.Add to the list of items declared in the schema. E.g.
CREATE TABLE supplier (CREATE TABLE supplier (snum CHAR(3), snum CHAR(3), sname VARCHAR(15), sname VARCHAR(15), status INT, status INT, city VARCHAR(15)city VARCHAR(15)CONSTRAINT pk_supplier PRIMARY KEY(snum)CONSTRAINT pk_supplier PRIMARY KEY(snum)
););
44 © D. Wong 2003© D. Wong 2003
Keys (continued)Keys (continued)
Primary Key attribute cannot be NULLPrimary Key attribute cannot be NULL
2 tuples in R cannot agree on all of the attributes in the 2 tuples in R cannot agree on all of the attributes in the primary key. DBMS rejects violating insertions or updates.primary key. DBMS rejects violating insertions or updates.
Can also declare a key with UNIQUECan also declare a key with UNIQUE
– Can be used instead of PRIMARY KEYCan be used instead of PRIMARY KEY
– Can have multiple UNIQUE in a tableCan have multiple UNIQUE in a table
– UNIQUE attributes permit NULLUNIQUE attributes permit NULL
Key constraints are checked at insert and updatesKey constraints are checked at insert and updates
Use of index created with key attributes for efficient key Use of index created with key attributes for efficient key enforcement checksenforcement checks
55 © D. Wong 2003© D. Wong 2003
Foreign-Key ConstraintsForeign-Key Constraints
To enforce referential integrity constraintsTo enforce referential integrity constraints
E.g. SPJ (type 1), S, P, J (type 2) E.g. SPJ (type 1), S, P, J (type 2)
The reference attribute of the relation of type 2 The reference attribute of the relation of type 2 must be declared PRIMARY or UNIQUEmust be declared PRIMARY or UNIQUE
Again 2 ways to declare in CREATE TABLEAgain 2 ways to declare in CREATE TABLE
1.1. Inline with declarationInline with declaration
2.2. Add to the list of items declared in the schemaAdd to the list of items declared in the schema
66 © D. Wong 2003© D. Wong 2003
FK as list of items declared in the schema e.g.FK as list of items declared in the schema e.g.
CREATE TABLE spj (CREATE TABLE spj (
snum CHAR(3), snum CHAR(3),
pnum CHAR(3),pnum CHAR(3),
jnum CHAR(3),jnum CHAR(3),
qty INT,qty INT,
CONSTRAINT fk_spj_1 FOREIGN KEY (snum) REFERENCES CONSTRAINT fk_spj_1 FOREIGN KEY (snum) REFERENCES S(snum) DEFERRABLE INITIALLY DEFERRED,S(snum) DEFERRABLE INITIALLY DEFERRED,
CONSTRAINT fk_spj_2 FOREIGN KEY (pnum) REFERENCES CONSTRAINT fk_spj_2 FOREIGN KEY (pnum) REFERENCES P(pnum) DEFERRABLE INITIALLY IMMEDIATE,P(pnum) DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT fk_spj_3 FOREIGN KEY (jnum) REFERENCES CONSTRAINT fk_spj_3 FOREIGN KEY (jnum) REFERENCES J(jnum)J(jnum) -- this one just use default, i.e. not DEFERRABLE -- this one just use default, i.e. not DEFERRABLE
););
77 © D. Wong 2003© D. Wong 2003
FK – maintaining referential integrityFK – maintaining referential integrity
3 Policies:3 Policies:
1.1. Default : Reject violating ModificationsDefault : Reject violating Modifications
2.2. Cascade : changes to the referenced attributes are Cascade : changes to the referenced attributes are mimicked at the foreign keymimicked at the foreign key
3.3. Set Null : set the foreign key to null when the Set Null : set the foreign key to null when the referenced attributes are changed (delete / update)referenced attributes are changed (delete / update)
Declare for delete and update separatelyDeclare for delete and update separately
Declare with the declaration of foreign keyDeclare with the declaration of foreign key
Dangling tuples – violate referential integrity constraint Dangling tuples – violate referential integrity constraint for the foreign key. Dealt with the 3 policies.for the foreign key. Dealt with the 3 policies.
88 © D. Wong 2003© D. Wong 2003
Maintaining referential integrity - ExampleMaintaining referential integrity - Example
CREATE TABLE spj (CREATE TABLE spj (
snum CHAR(3), snum CHAR(3),
pnum CHAR(3),pnum CHAR(3),
jnum CHAR(3),jnum CHAR(3),
qty INT,qty INT,
CONSTRAINT fk_spj_1 FOREIGN KEY (snum) REFERENCES CONSTRAINT fk_spj_1 FOREIGN KEY (snum) REFERENCES S(snum) ON S(snum) ON UPDATE CASCADEUPDATE CASCADE DEFERRABLE INITIALLY DEFERRABLE INITIALLY DEFERRED,DEFERRED,
CONSTRAINT fk_spj_2 FOREIGN KEY (pnum) REFERENCES CONSTRAINT fk_spj_2 FOREIGN KEY (pnum) REFERENCES P(pnum) ON P(pnum) ON DELETE SET NULLDELETE SET NULL DEFERRABLE INITIALLY DEFERRABLE INITIALLY IMMEDIATE,IMMEDIATE,
CONSTRAINT fk_spj_3 FOREIGN KEY (jnum) REFERENCES CONSTRAINT fk_spj_3 FOREIGN KEY (jnum) REFERENCES J(jnum)J(jnum) -- just use default -- just use default
););
99 © D. Wong 2003© D. Wong 2003
Constraints on Attributes and TuplesConstraints on Attributes and Tuples
Limits the values of some attributes.Limits the values of some attributes.
Constraints within relationsConstraints within relations
Defined in relation's schema as:Defined in relation's schema as:
1.1. Constraints on an attributeConstraints on an attribute
2.2. Constraints on tuples Constraints on tuples
1010 © D. Wong 2003© D. Wong 2003
Constraints on the attributesConstraints on the attributes
Not-null constraintsNot-null constraintse.g. pnum CHAR(3) NOT NULL,e.g. pnum CHAR(3) NOT NULL,
CONSTRAINT fk_spj_2 FOREIGN KEY (pnum) CONSTRAINT fk_spj_2 FOREIGN KEY (pnum) REFERENCES P(pnum) ,REFERENCES P(pnum) ,
Attribute-Based CHECKAttribute-Based CHECK
– Checked whenever any tuple gets a new value for this Checked whenever any tuple gets a new value for this attribute (e.g. update, insert)attribute (e.g. update, insert)
– Reject violating operationsReject violating operations
– The check is expressed as a conditional expression The check is expressed as a conditional expression
e.g. e.g. qty INT CHECK (qty <= 10000),qty INT CHECK (qty <= 10000),
– Invisible to other relations (so, can be violated if the Invisible to other relations (so, can be violated if the relations referenced in the condition are changed)relations referenced in the condition are changed)
– More examples in text Pp. 328 ex. 7.8, 7.9More examples in text Pp. 328 ex. 7.8, 7.9
1111 © D. Wong 2003© D. Wong 2003
Tuple-Based CHECK ConstraintsTuple-Based CHECK Constraints
Applies to one or more attributes of a tableApplies to one or more attributes of a table
Checked when a tuple is inserted or updated. Reject if it's Checked when a tuple is inserted or updated. Reject if it's a violating operation.a violating operation.
Invisible to other relations (so, can be violated if the Invisible to other relations (so, can be violated if the relations referenced in the condition are changed)relations referenced in the condition are changed)
E.g.E.g.
CREATE TABLE MovieStar(CREATE TABLE MovieStar(
name CHAR(30) PRIMARY KEY,name CHAR(30) PRIMARY KEY,
gender CHAR(1),gender CHAR(1),
CHECK (gender = 'F' OR name NOT LIKE'Ms.%')CHECK (gender = 'F' OR name NOT LIKE'Ms.%')
););
1212 © D. Wong 2003© D. Wong 2003
Modification of ConstraintsModification of Constraints
Only to constraints that are named.Only to constraints that are named.
Naming of constraints examples:Naming of constraints examples:
1.1. snum char (5) snum char (5) CONSTRAINT CONSTRAINT pk_supplierpk_supplier
PRIMARY KEY ,PRIMARY KEY ,
2.2. CONSTRAINT CONSTRAINT fk_spj_1fk_spj_1 FOREIGN KEY (snum) FOREIGN KEY (snum) REFERENCES S(snum) DEFERRABLE,REFERENCES S(snum) DEFERRABLE,
3.3. Gender CHAR(1) Gender CHAR(1) CONSTRAINT CONSTRAINT NoAndroNoAndro
CHECK (gender in ('F', 'M')),CHECK (gender in ('F', 'M')),
1313 © D. Wong 2003© D. Wong 2003
ModificationsModifications
Delete constraintsDelete constraints
ALTER TABLE <tableName> DROP CONSTRAINT ALTER TABLE <tableName> DROP CONSTRAINT <constraintName>;<constraintName>;
Add constraintAdd constraint
ALTER TABLE <tableName> ADD CONSTRAINT ALTER TABLE <tableName> ADD CONSTRAINT <constraintName> <constraint specification>;<constraintName> <constraint specification>;
e.g. ALTER TABLE student ADD CONSTRAINT e.g. ALTER TABLE student ADD CONSTRAINT PK_student PRIMARY KEY (studentkey);PK_student PRIMARY KEY (studentkey);
Set constraint – to change a deferrable constraint from Set constraint – to change a deferrable constraint from immediate to deferred and vise versaimmediate to deferred and vise versa
SETSET CONSTRAINT <constraintName> DEFERRED;CONSTRAINT <constraintName> DEFERRED;
1414 © D. Wong 2003© D. Wong 2003
AssertionsAssertions
An assertion is a schema level CHECK constraint.An assertion is a schema level CHECK constraint. Exist independent of any particular table.Exist independent of any particular table. It's condition can refer to any table in the db schemaIt's condition can refer to any table in the db schema Declaring an assertion:Declaring an assertion:
CREATE ASSERTION <constraintName>CREATE ASSERTION <constraintName>
CHECK <condition>CHECK <condition>
[constraint attributes];[constraint attributes]; constraint attributes: [NOT] DEFERRABLE; INITIALLY constraint attributes: [NOT] DEFERRABLE; INITIALLY
IMMEDIATE; INITIALLY DEFERREDIMMEDIATE; INITIALLY DEFERRED The constraint is violated if the condition is falseThe constraint is violated if the condition is false Any db modifications that causes a violation will be Any db modifications that causes a violation will be
rejectedrejected
1515 © D. Wong 2003© D. Wong 2003
TriggersTriggers
Available in Oracle and SQL99Available in Oracle and SQL99
Event-Condition-Action rules: define an action Event-Condition-Action rules: define an action the db should take when some db-related events the db should take when some db-related events occursoccurs
Triggers are useful for:Triggers are useful for:
1.1. To maintain complex integrity constraintsTo maintain complex integrity constraints
2.2. To audit changes made to tableTo audit changes made to table
3.3. To signal to other programs that changes To signal to other programs that changes were made to a tablewere made to a table
1616 © D. Wong 2003© D. Wong 2003
Trigger vs. other constraintsTrigger vs. other constraints
1.1. Triggers are awakened when certain events, Triggers are awakened when certain events, specified by db programmer, occur. E.g. update, specified by db programmer, occur. E.g. update, insert, delete to a relation; end of a transactioninsert, delete to a relation; end of a transaction
2.2. Other constraints immediately prevent the event Other constraints immediately prevent the event if the constraint is violated. For trigger, it's if the constraint is violated. For trigger, it's condition is tested when the event occurs, if the condition is tested when the event occurs, if the condition does not hold, then the action condition does not hold, then the action associated with the trigger will not happen (I.e. associated with the trigger will not happen (I.e. trigger will not be fired)trigger will not be fired)
3.3. If the trigger condition is true, the action is If the trigger condition is true, the action is performed by the DBMS (I.e. trigger fired). So, performed by the DBMS (I.e. trigger fired). So, it's transparent to the userit's transparent to the user
1717 © D. Wong 2003© D. Wong 2003
Trigger SyntaxTrigger Syntax
CREATE [OR REPLACE] TRIGGER <triggerName>CREATE [OR REPLACE] TRIGGER <triggerName>
{BEFORE | AFTER | INSTEADOF}{BEFORE | AFTER | INSTEADOF}
{DELETE | INSERT | UPDATE [of column, …] }{DELETE | INSERT | UPDATE [of column, …] }
[OR {DELETE | INSERT | UPDATE [of column, …] }[OR {DELETE | INSERT | UPDATE [of column, …] }
ON {tableName | viewName}ON {tableName | viewName}
[REFERENCING { OLD [AS] <oldName> , NEW [AS] [REFERENCING { OLD [AS] <oldName> , NEW [AS] <newName> …]<newName> …]
FOR EACH {ROW | STATEMENT} FOR EACH {ROW | STATEMENT}
[WHEN (condition) ] <action>;[WHEN (condition) ] <action>;
1818 © D. Wong 2003© D. Wong 2003
Oracle TriggersOracle Triggers
<action> is PL/SQL block<action> is PL/SQL block
Simplest is :Simplest is :
BEGINBEGIN
<SQL statement><SQL statement>
END;END;
In the PL/SQL action block, variables OLD and NEW are preceded In the PL/SQL action block, variables OLD and NEW are preceded by : e.g. :OLDby : e.g. :OLD
Follow the create trigger statement with a Dot (.) and then RUN to Follow the create trigger statement with a Dot (.) and then RUN to store the definition in the dbstore the definition in the db
The action cannot change the relation that triggers the action, nor to The action cannot change the relation that triggers the action, nor to relations connected to the triggering relation by a constraint e.g. FK relations connected to the triggering relation by a constraint e.g. FK constraintconstraint
Read 7.4.2 – 7.4.4Read 7.4.2 – 7.4.4
1919 © D. Wong 2003© D. Wong 2003
SQL3 TriggersSQL3 Triggers
<action> can be:<action> can be:
1.1. a single SQL statementa single SQL statement
2.2. A SQL statements, separated by ; enclosed in a A SQL statements, separated by ; enclosed in a
BEGINBEGIN
<SQL statements><SQL statements>
END;END;
2020 © D. Wong 2003© D. Wong 2003
Constraints SummaryConstraints Summary
1.1. Primary Key declarationPrimary Key declaration
2.2. Foreign Key – referential integrity constraintForeign Key – referential integrity constraint
3.3. Constraints within relations:Constraints within relations:
Attribute constraints: 1. NOT NULL; 2. Attribute constraints: 1. NOT NULL; 2. CHECKCHECK
Tuple based CHECKsTuple based CHECKs
4.4. Schema level constraints – SQL2 assertions (not Schema level constraints – SQL2 assertions (not in Oracle)in Oracle)
5.5. Triggers – Oracles's and SQL99'sTriggers – Oracles's and SQL99's
2121 © D. Wong 2003© D. Wong 2003
Ch. 8 - System Aspects of SQLCh. 8 - System Aspects of SQL
SQL in programming environmentsSQL in programming environments
– Statement Level InterfaceStatement Level InterfaceEmbedded SQL, Embedded SQL, SQLJSQLJDynamic SQLDynamic SQL
– PSMPSMOracle’s PL/SQLOracle’s PL/SQL
– Call Level InterfaceCall Level Interface
SQL environmentSQL environment
2222 © D. Wong 2003© D. Wong 2003
Host Language InterfaceHost Language Interface
Host language: conventional language that applications are Host language: conventional language that applications are written in. e.g C, Java, C#, Visual Basic .Netwritten in. e.g C, Java, C#, Visual Basic .Net
Statement level interfaceStatement level interface
– Static: Embedded SQL, SQLJStatic: Embedded SQL, SQLJ
– Dynamic SQLDynamic SQL
Call level interface (CLI)Call level interface (CLI)
Use of CLI (e.g. JDBC) for static transaction is less Use of CLI (e.g. JDBC) for static transaction is less efficient at run time than statement-level interfaces efficient at run time than statement-level interfaces because CLI’s preparation and execution generally involve because CLI’s preparation and execution generally involve separate communications with the DBMS, which is costly.separate communications with the DBMS, which is costly.
2323 © D. Wong 2003© D. Wong 2003
Embedded SQLEmbedded SQL
Shared variables Shared variables
– Host language variables that can be read/written by Host language variables that can be read/written by SQL statementSQL statement
– Serves as interface between the host language and the Serves as interface between the host language and the SQL execution systemSQL execution system
– When used in embedded SQL statements, precede the When used in embedded SQL statements, precede the variable with a : e.g. :namevariable with a : e.g. :name
Embedded SQL statements are prefixed with EXEC SQLEmbedded SQL statements are prefixed with EXEC SQL
Preprocessor translate the EXEC SQL statements into Preprocessor translate the EXEC SQL statements into function calls in host language, then compile, linked with function calls in host language, then compile, linked with SQL-related library to form executable code. Fig. 8.1 pp SQL-related library to form executable code. Fig. 8.1 pp 351351
2424 © D. Wong 2003© D. Wong 2003
Embedded SQL (continued)Embedded SQL (continued)
SQLSTATESQLSTATE
– a special variable (an array of 5 char) a special variable (an array of 5 char)
– Serves to connect the host-language program Serves to connect the host-language program with the SQL execution systemwith the SQL execution system
– updated each time a SQL library function is updated each time a SQL library function is calledcalled
– Some of the codes are:Some of the codes are:‘‘00000’ = no error00000’ = no error‘‘02000’ = no tuple found02000’ = no tuple found
2525 © D. Wong 2003© D. Wong 2003
Embeddable SQL statementsEmbeddable SQL statements
Any SQL statement that does not return a result (I.e. not Any SQL statement that does not return a result (I.e. not a select-from-where query) can be embedded. E.g. insert, a select-from-where query) can be embedded. E.g. insert, delete, create, update.delete, create, update.
select-from-where queries are not embeddable directly. select-from-where queries are not embeddable directly.
For connecting the result of queries with a host-language For connecting the result of queries with a host-language program, must use one of the following methods:program, must use one of the following methods:
1.1. Use single-row select for query that produces a single Use single-row select for query that produces a single tuple : select-into-from-where. Ref. fig. 8.3 pp 355tuple : select-into-from-where. Ref. fig. 8.3 pp 355
EXEC SQL SELECTEXEC SQL SELECT A A INTOINTO :var :var FROMFROM R R WHEREWHERE <cond>;<cond>;
2.2. Use CURSOR for queries producing more than one Use CURSOR for queries producing more than one tuple Fig. 8.4 pp 357tuple Fig. 8.4 pp 357
2626 © D. Wong 2003© D. Wong 2003
CURSOR - CURSOR - Ref. Fig. 7.4 pp.379 (Fig. 8.4 pp 357)Ref. Fig. 7.4 pp.379 (Fig. 8.4 pp 357)
An object used to store the output of a query for processing An object used to store the output of a query for processing in an application. It provides the mechanism to reference in an application. It provides the mechanism to reference the current position in a result set, and to do positioned the current position in a result set, and to do positioned updates and deletes.updates and deletes.
Declare cursor in embedded SQL by:Declare cursor in embedded SQL by:
EXEC SQL DECLARE <cursor> CURSOR FOR <query>EXEC SQL DECLARE <cursor> CURSOR FOR <query> Open cursor before use: Open cursor before use:
EXEC SQL OPEN <cursor>EXEC SQL OPEN <cursor> Use Fetch statement to get the next tuple of the relation Use Fetch statement to get the next tuple of the relation
over which the cursor rangeover which the cursor range
EXEC SQLFETCH FROM <cursor> INTO <list of shared EXEC SQLFETCH FROM <cursor> INTO <list of shared variables>variables>
SQLSTATE of ‘02000’ means no more tuples foundSQLSTATE of ‘02000’ means no more tuples found To close a cursor when done: To close a cursor when done: EXEC SQL CLOSEEXEC SQL CLOSE
2727 © D. Wong 2003© D. Wong 2003
Cursor optionsCursor options
INSENSITIVE INSENSITIVE
guarantee that changes to underlying relation made guarantee that changes to underlying relation made between one opening and closing of cursor will not between one opening and closing of cursor will not affect the set of tuples already fetched.affect the set of tuples already fetched.
FOR READ ONLYFOR READ ONLY
DBMS will prevent modifications to the underlying DBMS will prevent modifications to the underlying relation through this cursorrelation through this cursor
SCROLLSCROLL
The cursor may be accessed with any one of the :The cursor may be accessed with any one of the :
FETCH {NEXT / PRIOR/ FIRST / LAST /RELATVE n/ FETCH {NEXT / PRIOR/ FIRST / LAST /RELATVE n/ ABSOLUTE n}ABSOLUTE n}
ResultSet in JDBC is a cursorResultSet in JDBC is a cursor
2828 © D. Wong 2003© D. Wong 2003
SQLJSQLJ
ANSI standard Statement-level Interface to JAVAANSI standard Statement-level Interface to JAVA A dialect of embedded SQL that can be included in JAVA A dialect of embedded SQL that can be included in JAVA
programprogram Goal: Goal:
To obtain the run-time efficiency of embedded SQL for To obtain the run-time efficiency of embedded SQL for Java applications while retaining the advantage of Java applications while retaining the advantage of accessing DBMS through JDBCaccessing DBMS through JDBC
Embedded SQLJ constructs are replaced by calls to an Embedded SQLJ constructs are replaced by calls to an SQLJ run-time package, which access database using SQLJ run-time package, which access database using JDBC.JDBC.
Benefit: the pre-compiler (translator in Oracle) can check Benefit: the pre-compiler (translator in Oracle) can check SQL syntax and the number and types of arguments and SQL syntax and the number and types of arguments and results.results.
2929 © D. Wong 2003© D. Wong 2003
Differences between SQLJ, Embedded SQL and JDBCDifferences between SQLJ, Embedded SQL and JDBC
1.1. SQLJ supports essentially SQL-92, much more portable SQLJ supports essentially SQL-92, much more portable across DBMS vendors. For embedded SQL, each DBMS across DBMS vendors. For embedded SQL, each DBMS vendor supports its own proprietary version of SQL.vendor supports its own proprietary version of SQL.
2.2. An SQLJ clause in a JAVA program begin with #SQL An SQLJ clause in a JAVA program begin with #SQL instead of EXEC SQL, and can contain select-from-where instead of EXEC SQL, and can contain select-from-where statement inside { }statement inside { }
3.3. Any JAVA variables can be included as a parameter in an Any JAVA variables can be included as a parameter in an SQL statement (prefix the variable with : ) , same as in SQL statement (prefix the variable with : ) , same as in embedded SQLembedded SQL
4.4. In SQLJ, a query returns an SQLJ interator object In SQLJ, a query returns an SQLJ interator object instead of a ResultSet object (as in JDBC). But, it’s similar instead of a ResultSet object (as in JDBC). But, it’s similar to ResultSet in that they provide a cursor mechanism.to ResultSet in that they provide a cursor mechanism.
5.5. Both SQLJ statement and JDBC calls can be included in Both SQLJ statement and JDBC calls can be included in the same Java programthe same Java program
3030 © D. Wong 2003© D. Wong 2003
Oracle’s SQLJ scriptOracle’s SQLJ script
To use: sqlj file.sqlj To use: sqlj file.sqlj Many command lines options are availabe, refer to Many command lines options are availabe, refer to
Oracle developer guide at Oracle developer guide at http://http://otnotn.oracle.com/tech/java/.oracle.com/tech/java/sqljsqlj__jdbcjdbc//pdfpdf/a96655./a96655.pdfpdf
Invokes translator to preprocess java programs Invokes translator to preprocess java programs with SQLJ clauses (suffix of those files can with SQLJ clauses (suffix of those files can be .sqlj, .java). Translator generates .java file be .sqlj, .java). Translator generates .java file which contains the JDBC calls for the SQL which contains the JDBC calls for the SQL statementsstatements
Invokes javac to compile Invokes javac to compile
Invokes JVM to executeInvokes JVM to execute
3131 © D. Wong 2003© D. Wong 2003
Dynamic SQLDynamic SQL
Used when the SQL statement is not known at Used when the SQL statement is not known at compile timecompile time
E.g. an application that prompt the user for an E.g. an application that prompt the user for an SQL query, read, and then execute the query SQL query, read, and then execute the query (can you think of an application?)(can you think of an application?)
Host language program must instruct SQL to:Host language program must instruct SQL to:
1.1. Take a string and turn it into an executable Take a string and turn it into an executable SQL statement:SQL statement:
EXEC SQL PREPARE sqlvar FROM sharedVar;EXEC SQL PREPARE sqlvar FROM sharedVar;
2.2. Execute the prepared statement:Execute the prepared statement: EXEC SQL EXECUTE sqlvar;EXEC SQL EXECUTE sqlvar;
3232 © D. Wong 2003© D. Wong 2003
Dynamic SQL (continued)Dynamic SQL (continued)
Steps 1 and 2 can be combined by:Steps 1 and 2 can be combined by:
EXEC SQL EXECUTE IMMEDIATE sharedVar;EXEC SQL EXECUTE IMMEDIATE sharedVar;
The 2 steps approach is beneficial if a prepared The 2 steps approach is beneficial if a prepared statement is execute multiple times.statement is execute multiple times.
Ref. Fig. 8.7 pp. 368 Ref. Fig. 8.7 pp. 368
Recommended