Download presentation
Presentation is loading. Please wait.
1
Embedded DB2
2
Agenda Supporting Embedded SQL Coding Aids Program Preparation
Delimiters Host Variables Indicator Variables SQLCA Coding Aids Program Preparation Using Cursors
3
Supporting Embedded SQL
4
Objectives Embed INSERT, UPDATE, DELETE and single row SELECT statements in application programs Effectively communicate with DB2 by using indicators and the SQLCA block Demonstrate use of DB2 coding aids
5
Supporting Embedded SQL
Use delimiters to identify SQL statements in the application Use host variables to provide values on the WHERE clauses or receive values from SELECT statements Use Indicator variables to provide null data Use the SQLCA to determine success or failure of SQL statements
6
Delimiters Used by PRECOMPILER to identify SQL statements to be translated Must indicate beginning and end of each embedded SQL statement C and C++ Delimiters EXEC SQL <SQL statement> ; The keywords EXEC SQL must appear on the same line
7
Delimiters in C and C++ EXEC SQL UPDATE TEMPL SET WORKDEPT = ‘C02’ WHERE WORKDEPT = ‘C01’ ;
8
Host Variables (I) C Andy gets(sname); User Inputs a Value name Andy
ESQL where sname= :name Optional, used to set a value before statement is executed Host variables must be preceded by a colon Host variables must match column data types
9
Host Variables (II) Interactive SQL statement
INSERT INTO S (s#, sname) VALUES (‘000122’, ‘Claven’) SQL Statement in A Program EXEC SQL INSERT INTO S (s#,sname) VALUES (:sid, :sname) ; 000122 Claven sid sname
10
Host Variables (III) Interactive SQL statement
UPDATE SC SET score = score * 1.05 WHERE c# = ‘c01’ SQL Statement in A Program EXEC SQL UPDATE SC SET score = score * :ratio WHERE c#= :cid ; 1.05 c01 ratio cid
11
Host Variable (IV) To Receive a Value SELECT........INTO :a ..... a
Required with SELECT statement One HOST VARIABLE for each COLUMN SELECTed Additional variable used for indicating NULL characteristic SELECT INTO syntax can only be used to return one or zero rows. GROUP BY, HAVING, ORDER BY are not permitted.
12
Host Variables Declaration
EXEC SQL BEGIN DECLARE SECTION; (Declaration of all host variables referenced within SQL statements) EXEC SQL END DECLARE SECTION; Global to a module Multiple declare sections may be used in one source file
13
Declaration Considerations For C
CREATE TABLE SIMPLE (title char(20), number smallint) EXEC SQL BEGIN DECLARE SECTION; char title[21]; short number; EXEC SQL END DECLARE SECTION; main() { EXEC SQL SELECT TITLE INTO :title FROM SIMPLE WHERE number= :number; }
14
Indicator Variables(I)
SELECT col1 INTO :a:ind a aind - value INDICATOR VARIABLE (SMALLINT) is required if SELECTed column allows NULL. If column is NULL, INDICATOR VARIABLE is set to negative value, VALUE VARIABLE is untouched. INDICATOR VARIABLE can be set to negative value by program to indicate NULL on UPDATE or INSERT
15
Indicator Variable (II)
If DB2 attempts to indicate the presence of a NULL and the program does not provide an indicator variable, an error results. Sample C declare for an indicator: EXEC SQL BEGIN DECLARE SECTION; short aind; char a[9]; EXEC SQL END DECLARE SECTION;
16
Indicator Logic Example
EXEC SQL SELECT phoneno, sex INTO :phoneno:phoneind, :sex FROM TEMPL WHERE empno = :eno; if (phoneind < 0) null_phone(); else good_phone();
17
Indicator Variable Usage NULL Values
HOST VAR IND. VAR COLUMN :cd :cdi jobcode unchanged < 0 NULL N/A <0 NULL SELECT/ FETCH UPDATE/ INSERT : Controlled By DB2 : Controlled By Program
18
Indicator Variable Usage Truncation
If an indicator variable has a positive value, a truncation occurred. If the seconds portion of a TIME data type is truncated, the indicator variable contains the second portion of the data. For all other data types, the indicator variable represents the length of the data in the database column.
19
SQLCA - SQL Communication Area
Information/SQLCODE Program SQLCA DB2 SQL An ESQL application program must either provide a structure named SQLCA or a stand-alone integer variable named SQLCODE.
20
SQLCA Code Condition SQLCODE SQLWARNO REQUEST STATUS
ERROR < FAILED WARNING > 0 & != OR ‘W’ SPECIAL COND. NOT FOUND DATA NOT FOUND SUCCESS AND ‘ ‘ SUCCESS
21
Coding Aids WHENEVER Statement for exception handling
INCLUDE statement and INCLUDE files to add SQLCA structure to program and to provide function prototypes
22
WHENEVER Statement EXEC SQL WHENEVER condition action; Conditions:
SQLERROR - negative SQLCODE SQLWARNING - position SQLCODE(not +100) or SQLWARNO = ‘W’ NOT FOUND - SQLCODE = +100 Actions: GOTO :X CONTINUE Program continues with next statement used to cancel effect of prior WHENEVER
23
WHENEVER Example EXEC SQL WHENEVER SQLWARNING GOTO :w;
EXEC SQL WHENEVER NOT FOUND GOTO :m; EXEC SQL WHENEVER SQLERROR GOTO :oh_no; EXEC SQL WHENEVER SQLERROR CONTINUE;
24
SQL Include Statement file.sqc file.c
EXEC SQL INCLUDE SQLCA; EXEC SQL BEGIN DECLARE SECTION; EXEC SQL INCLUDE ‘myfile.h’; EXEC SQL END DECLARE SECTION; struct sqlca .... }; struct sqlca sqlca; /* myfile.h contains my host variables */ If myfile.h contains host variable declarations, it must be included with the EXEC SQL INCLUDE.
25
Include Files #include <sqlca.h> struct sqlca sqlca;
#include <sql.h> functions prototypes for certain API’s including error message retrieval. sqlda.h : defines the SQL Descriptor Area(SQLDA) sqlenv.h : language-specific calls for database environment APIs, and the structure, constants, and return codes for those interfaces. sqlutil.h : language-specific calls for the utility APIs, and the structure, constants, and return codes for those interfaces.
26
Program Preparation
27
Objectives Identify the additional steps necessary to prepare a program that contains embedded SQL for execution describe the functions of the DB2 PRECOMPILE and BIND processes
28
Precompile(I) P Database R Tables Services E Indexes C myapp.sqc
Package myapp.sqc Source File myapp.c Name of package: The same as the name of the source module truncated to 8 characters Modified Source File
29
Precompile(II) PREPARE or PREP
By Default, PREP creates a package directly in the database. By Default the PREP produces two output Modified source file: Replace SQL with host language calls Use DB2 Optimizer to create an access strategy called package Index? Object exists? Authority? Time Stamp: Include in package and modified source file db2 PREP myapp.sqc
30
Compile and Link The modified source file is compiled and linked normally, producing an executable file. gcc -I/usr/include -ldb2 myapp.c -o myapp
31
Program Execution Package Tables Myapp Database Services
Executable File
32
Precompile with Bindfile(I)
myapp.bnd myapp.sqc Bind File Source File myapp.c Modified Source File
33
Precompile with Bindfile(II)
When the BINDFILE option is used, two outputs are produced. Modified source file Bind File: A package is not automatically created. A separate bind step must be run to produce a package. db2 PREP myapp.sqc BINDFILE BIND An Application Program db2 BIND <bind file>
34
Privileges Required for Programming
Action Privileges Required Precompile to bindfile CONNECT on DATABASE Create a new package CONNECT on DATABASE BINDADD on DATABASE Privileges need to execute each static SQL statement Modify a package CONNECT on DATABASE BIND on package Recreate a package CONNECT on DATABASE Execute a package CONNECT on DATABASE EXECUTE on package Drop a package CONNECT on DATABASE CONTROL on package or creator of package
35
Rebinding Implicit rebinding is automatic at next execution if
drop object referenced in package drop primary key on table referenced in package drop/add referential constraint on parent or child table referenced in package revoke privilege required by binder to execute static SQL statement embedded in package
36
Explicit Rebinding Rebinding - recreating a package for an application program that was previously bound Why? Take advantage of newly created index Make use of updated statistics after executing the RUNSTATS command Take control over when the rebinding occurs
37
Cursors in Embedded SQL
38
Objectives How to use DECLARE, OPEN, FETCH, and CLOSE CURSOR statements to handle select criteria that may return multiple rows UPDATE and DELETE rows identified by CURSORS
39
Processing Multiple Rows(I)
SELECT SNAME DEPT Claven cc Natural cis Yzchen csie SNAME DEPT FETCH SNAME DEPT Claven cc Natural cis Yzchen csie Claven cc SNAME DEPT
40
Processing Multiple Rows(II)
FETCH SNAME DEPT Claven cc Natural cis Yzchen csie Natural cis SNAME DEPT FETCH SNAME DEPT Claven cc Natural cis Yzchen csie Yzchen csie SNAME DEPT
41
Processing Multiple Rows(III)
No method to determine the number of rows that will satisfy the WHERE clause of a SELECT statement in advance Use CURSORS to process sets of data The CURSOR is used to retrieve one row of data at a time Each FETCH of the cursor retrieves the next row in the set of data that met the WHERE clause
42
SELECT with FETCH (I) Define a CURSOR Example
EXEC SQL DECLARE <Cursor Name> CURSOR FOR <Select Clause> ; Example EXEC SQL DECLARE k9 CURSOR FOR SELECT empno, lastname FROM TEMPL WHERE DEPT= :dept;
43
SELECT with FETCH(II) OPEN the CURSOR FETCH RESULT ROWS ONE AT A TIME
EXEC SQL OPEN <Cursor Name>; EXEC SQL OPEN k9 Values assigned to host variables are relevant at OPEN FETCH RESULT ROWS ONE AT A TIME EXEC SQL FETCH <Cursor Name> INTO <host variables> EXEC SQL FETCH k9 INTO :empno, :name; Need a loop to fetch all result sets until SQLCODE 100 is returned
44
SELECT with FETCH (III)
CLOSE CURSOR when finished EXEC SQL CLOSE <Cursor Name>; EXEC SQL CLOSE k9;
45
DELETE Via A Cursor EXEC SQL DECLARE ce CURSOR FOR ...;
EXEC SQL OPEN ce; while (SQLCODE != 100) { EXEC SQL FETCH ce INTO ....; EXEC SQL DELETE FROM TEMPL WHERE CURRENT OF ce; .... EXEC SQL CLOSE ce;
46
UPDATE Via A Cursor EXEC SQL DECLARE cx CURSOR FOR SELECT empno, lastname FROM TEMPL WHERE deptno = :dpt FOR UPDATE OF lastname; EXEC SQL OPEN cx; EXEC SQL UPDATE TEMPL SET lastname = :newname WHERE CURRENT OF cx; .....
47
UPDATE/DELETE Via A Cursor
DECLARE CURSOR statement may not contain “FOR UPDATE OF”, nor may the cursor be used for “DELETE WHERE CURRENT OF”, if the SELECT statement contains: GROUP BY ORDER BY DISTINCT UNION, EXCEPT, INTERSECT function join FOR FETCH ONLY
48
Privileges Privileges convey the right to perform a specific action on a specific object.
49
Table and View Privileges
Control ALTER DELETE INDEX INSERT REFERENCES SELECT UPDATE View: Privileges on the underlying objects. Create a View: SELECT and CONTROL INSERT/UPDATE/DELETE
50
Index and Package Privileges
CONTROL Privilege Package: CONTROL EXECUTE BIND
51
GRANT GRANT <privilege>|ALL ON [TABLE] <table> TO [USER] <user>|GROUP <group>|PUBLIC GRANT CONTROL ON INDEX <index> TO [USER] <user>|GROUP <group>|PUBLIC GRANT <privilege>|ALL ON PACKAGE <package> TO [USER] <user>|GROUP <group>|PUBLIC Example: GRANT SELECT, INSERT ON test.table1 TO t1, t2; GRANT BIND, EXECUTE ON PACKAGE ap1 TO PUBLIC;
52
REVOKE REVOKE <privilege>|ALL ON [TABLE] <table> FROM [USER] <user>|GROUP <group>|PUBLIC REVOKE CONTROL ON INDEX <index> FROM [USER] <user>|GROUP <group>|PUBLIC REVOKE <privilege>|ALL ON PACKAGE <package> FROM [USER] <user>|GROUP <group>|PUBLIC Example: REVOKE ALL PRIVILEGES ON table1 FROM USER freddy; REVOKE CONTROL ON INDEX i1 FROM smith, jones;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.