8. programatic sql.ppt
TRANSCRIPT
Programmatic SQL
1
Learning Outcomes
Pada akhir pertemuan ini, diharapkan mahasiswa dapat mendemonstrasikan bagaimana SQL dapat diintegrasikan di dalam high level programming language (C3)(C3)
2
Outline Materi
• How SQL statements can be embeddedin high-level programming languages.
• Difference between static and dynamicembedded SQL.
• How to write programs that use static• How to write programs that use staticembedded SQL.
• How to write programs that usedynamic embedded SQL.
3
Embedded SQL
• SQL can be embedded in high-levelprocedural language.
• In many cases, language is identicalalthough SELECT statement differs.
• Two types of programmatic SQL:– Embedded SQL statements.– Embedded SQL statements.
• SQL supports Ada, C, COBOL,FORTRAN, MUMPS, Pascal, and PL/1.
– Application program interface (API).
4
Example 21.1 - CREATE TABLE
EXEC SQL CREATE TABLE Viewing (propertyNo VARCHAR2(5) NOT
NULL,clientNo VARCHAR2(5) NOT NULL,viewDate DATE NOT NULL,viewDate DATE NOT NULL,comment VARCHAR2(40));
if (sqlca.sqlcode >= 0)printf(“Creation successful\n”);
5
Embedded SQL
• Embedded SQL starts with identifier, usuallyEXEC SQL [ ‘@SQL(’ in MUMPS].
• Ends with terminator dependent on hostlanguage:– Ada, ‘C’, and PL/1: terminator is semicolon
(;)(;)– COBOL: terminator is END-EXEC– Fortran: ends when no more continuation
lines.• Embedded SQL can appear anywhere an
executable host language statement canappear.
6
SQL Communications Area (SQLCA)
• Used to report runtime errors to theapplication program.
• Most important part is SQLCODEvariable:
0 - statement executed successfully;0 - statement executed successfully;< 0 - an error occurred;> 0 - statement executed successfully, but
an exception occurred, such as no morerows returned by SELECT.
7
SQLCA for Oracle
8
WHENEVER Statement
• Every embedded SQL statement canpotentially generate an error.
• WHENEVER is directive to precompilerto generate code to handle errors afterto generate code to handle errors afterevery SQL statement:
EXEC SQL WHENEVER<condition> <action>
9
WHENEVER Statement
• condition can be:SQLERROR - generate code to handle errors
(SQLCODE < 0).SQLWARNING - generate code to handle warnings.NOT FOUND - generate code to handle specific
warning that a retrieval operation has found nowarning that a retrieval operation has found nomore records.
10
WHENEVER Statement
• action can be:CONTINUE - ignore condition and proceed to next
statement.
DO - transfer control to an error handling function.
DO BREAK - place an actual “break” statement inthe program.
DO CONTINUE - place an actual “continue”DO CONTINUE - place an actual “continue”statement in the program.
GOTO label or GO TO label - transfer control tospecified label.
STOP - rollback all uncommitted work and terminatethe program.
11
WHENEVER Statement
EXEC SQL WHENEVER SQLERROR GOTOerror1;
EXEC SQL INSERT INTO Viewing VALUES(‘CR76’, ‘PA14’, ‘12-May-2001’, ‘Not enoughspace’);
• would be converted to:
EXEC SQL INSERT INTO Viewing VALUES(‘CR76’, ‘PA14’, ‘12-May-2001’, ‘Not enoughspace’);
if (sqlca.sqlcode < 0) goto error1;12
Host Language Variables
• Program variable declared in hostlanguage.
• Used in embedded SQL to transfer datafrom database into program and viceversa.
• Can be used anywhere a constant canappear.
• Cannot be used to represent databaseobjects, such as table names or columnnames.
• To use host variable, prefix it by a colon (:).13
Host Language Variables
EXEC SQL UPDATE StaffSET salary = salary + :incrementWHERE staffNo = ‘SL21’;
• Need to declare host languagevariables to SQL, as well as to hostlanguage:language:
EXEC SQL BEGIN DECLARE SECTION;float increment;
EXEC SQL END DECLARE SECTION;
14
Indicator Variables
• Indicates presence of null:0 associated host variable contains validvalue.
<0 associated host variable should be assumedto contain a null; actual contents of hostvariable irrelevant.variable irrelevant.
>0 associated host variable contains validvalue.
• Used immediately following associatedhost variable with a colon (:)separating two variables.
15
Indicator Variables - Example
EXEC SQL BEGIN DECLARE SECTION;char address[51];short addressInd;
EXEC SQL END DECLARE SECTION;addressInd = -1;addressInd = -1;EXEC SQL UPDATE PrivateOwner
SET address = :address:addressInd
WHERE ownerNo = ‘CO21’;16
Singleton SELECT - Retrieves Single Row
EXEC SQL SELECT fName, lName, addressINTO :firstName, :lastName, :address
:addressIndFROM PrivateOwnerWHERE ownerNo = ‘CO21’;
• Must be 1:1 correspondence betweenexpressions in SELECT list and hostvariables in INTO clause.
• If successful, SQLCODE set to 0; ifthere are no rows that satisfiesWHERE, SQLCODE set to NOT FOUND.
17
Cursors
• If query can return arbitrary number ofrows, need to use cursors.
• Cursor allows host language to accessrows of query one at a time.
• Cursor acts as a pointer to a row ofquery result. Cursor can be advancedquery result. Cursor can be advancedby one to access next row.
• Cursor must be declared and openedbefore it can be used and it must beclosed to deactivate it after it is nolonger required.
18
Cursors - DECLARE CURSOR
• Once opened, rows of query result canbe retrieved one at a time using FETCH:
EXEC SQL DECLAREpropertyCursor CURSOR FOR
SELECT propertyNo, street, citySELECT propertyNo, street, cityFROM PropertyForRentWHERE staffNo = ‘SL41’;
19
Cursors - OPEN
• OPEN statement opens specifiedcursor and positions it before first rowof query result:
EXEC SQL OPEN propertyCursor;
20
Cursors - FETCH and CLOSE
• FETCH retrieves next row of query resulttable:
EXEC SQL FETCH propertyCursorINTO :propertyNo, :street, :city
• FETCH is usually placed in a loop. Whenthere are no more rows to be returned,SQLCODE is set to NOT FOUND.
EXEC SQL CLOSE propertyCursor;
21
ISO Standard for Embedded SQL
• Standard does not recognizeSQLWARNING of WHENEVER statement.
• Standard does not mention an SQLCA. Itdoes, however, recognize the integervariable SQLCODE, although this is adeprecated feature that is supported onlydeprecated feature that is supported onlyfor compatibility with earlier versions ofthe standard.
• Instead, defines a character stringSQLSTATE parameter, comprising a two-character class code followed by a three-character subclass code.
22
ISO Standard for Embedded SQL
• Standard specifies definition andprocessing of cursors slightlydifferently from that presented above.ISO DECLARE CURSOR is:EXEC SQL DECLARE cursorNameEXEC SQL DECLARE cursorName
[INSENSITIVE] [SCROLL]
CURSOR FOR selectStatement
[FOR {READ ONLY |
UPDATE [OF columnNameList]}]
23
ISO Standard for Embedded SQL
• FETCH statement:EXEC SQL FETCH [[fetchOrientation] FROM]
cursorName INTO hostVariable [, . . . ]
• fetchOrientation can be one of:– NEXT– NEXT
– PRIOR
– FIRST
– LAST
– ABSOLUTE
– RELATIVE
24
Dynamic Embedded SQL
• With static embedded SQL, cannot use hostvariables where database object names required.
• Dynamic SQL allows this.• Idea is to place complete SQL statement in a
host variable, which is passed to DBMS to beexecuted.
• If SQL statements do not involve multi-row• If SQL statements do not involve multi-rowqueries, use EXECUTE IMMEDIATE statement:
EXEC SQL EXECUTE IMMEDIATE[hostVariable | stringLiteral]
25
Dynamic Embedded SQL
For example:
sprintf(buffer, “UPDATE StaffSET salary = salary + %fWHERE staffNo = ‘SL21’ ”,WHERE staffNo = ‘SL21’ ”,
increment);EXEC SQL EXECUTE IMMEDIATE :buffer;
26
PREPARE and EXECUTE
• DBMS must parse, validate, and optimizeeach EXECUTE IMMEDIATE statement,build execution plan, and execute plan.
• OK if SQL statement is only executedonce in program; otherwise inefficient.
• Dynamic SQL provides alternative:PREPARE and EXECUTE.
• PREPARE tells DBMS to readydynamically built statement for laterexecution.
27
PREPARE and EXECUTE
• Prepared statement assigned name.When statement is subsequentlyexecuted, program need only specifythis name:
EXEC SQL PREPARE statementNameEXEC SQL PREPARE statementNameFROM [hostVariable | stringLiteral]
EXEC SQL EXECUTE statementName[ USING hostVariable [indicatorVariable] [, ...] |USING DESCRIPTOR descriptorName ]
28
Parameter Markers
• USING allows portions of preparedstatement to be unspecified, replacedby placeholders (parameter markers).
• Placeholder can appear anywhere in• Placeholder can appear anywhere inhostVariable or stringLiteral ofPREPARE that constant can appear.
• Tells DBMS value will be supplied later,in EXECUTE statement.
29
Placeholders
sprintf(buffer, “UPDATE StaffSET salary = :salWHERE staffNo = :sn”);
EXEC SQL PREPARE stmt FROM :buffer;EXEC SQL PREPARE stmt FROM :buffer;EXEC SQL EXECUTE stmt
USING :newSalary, :staffNo;
• sal and sn are placeholders.
30
Static versus Dynamic SQL
31
SQL Descriptor Area (SQLDA)
• Alternative way to pass parameters toEXECUTE statement is through SQLDA.
• Used when number of parameters andtheir data types unknown whenstatement formulated.statement formulated.
• SQLDA can also be used to dynamicallyretrieve data when do not know numberof columns to be retrieved or the typesof the columns.
32
SQLDA for Oracle
33
Retrieving Data Using Dynamic SQL
• Again, use cursors to retrieve data from a queryresult table that has an arbitrary number of rows.
EXEC SQL DECLARE cursorName CURSOR FOR selectStatement
EXEC SQL OPEN cursorName [FOR READONLY] EXEC SQL OPEN cursorName [FOR READONLY] {USING hostVariable [indicatorVariable] [,...] |USING DESCRIPTOR descriptorName }
EXEC SQL FETCH cursorName {INTO hostVariable [indicatorVariable] [,...] |USING DESCRIPTOR descriptorName }
EXEC SQL CLOSE cursorName
34
Retrieving Data Using DynamicSQL• OPEN allows values for placeholders
to be substituted using one or morehostVariables in:– USING clause or– passing values via descriptorName
(SQLDA) in a USING DESCRIPTOR(SQLDA) in a USING DESCRIPTORclause.
• Main difference is with FETCH, whichnow uses descriptorName to receiverows of query result table (or one ormore hostVariables/indicatorVariables).
35
Retrieving Data Using DynamicSQL
• Before FETCH, program must provide data areasto receive retrieved data and indicator variables.
• Basic steps for dynamic SQL statement are:
(1) Declare host string in DECLARE SECTION tohold text of the query.
(2) Declare a select SQLDA and, if required, a bindSQLDA.SQLDA.
(3) Allocate storage space for the SQLDA(s).
(4) Set maximum number of columns in selectSQLDA and, if query can have placeholders,maximum number of placeholders in bind SQLDA.
36
Retrieving Data Using DynamicSQL
(5) Put the query text into the host string.
(6) PREPARE the query from the host string.
(7) DECLARE a cursor for the query.
(8) If the query can have placeholders:(a) DESCRIBE bind variables into bind SQLDA.
(b) Reset number of placeholders to numberactually found by DESCRIBE.
(c) Get values and allocate storage space for bindvariables found by DESCRIBE.
(9) OPEN cursor USING the bind SQLDA, or ifno bind SQLDA has been used, USING theselect SQLDA.
37
Retrieving Data Using DynamicSQL
(10) DESCRIBE the column list INTO the select
SQLDA.
(11) Reset number of column list items to number
actually found by DESCRIBE.
(12) Reset length and data type of each column list
item.
(13) FETCH each row from database into allocated
data buffers pointed to by the select SQLDA and
process it, as appropriate.
(14) Deallocate the storage space used for the
column list items, placeholders, indicator
variables, and SQLDAs.38