05027240 Database systems       Database Application Development  Veera Boonjing [email_address] Semester  1/2547  King Mo...
Triggers
Trigger Overview <ul><li>Element of the database schema </li></ul><ul><li>General form:  ON  < event >  IF  < condition > ...
Trigger Details <ul><li>Activation  - Occurrence of the  event </li></ul><ul><li>Consideration  - The point, after activat...
Trigger Details <ul><li>Execution  - point at which  action  occurs </li></ul><ul><ul><li>With deferred consideration, exe...
Trigger Details <ul><li>Granularity  -  </li></ul><ul><ul><li>Row-level granularity:  change of a single row is an event (...
Trigger Details <ul><li>Multiple Triggers  </li></ul><ul><ul><li>How should multiple triggers activated by a single event ...
Triggers in SQL/3 <ul><li>Events :  INSERT, DELETE , or  UPDATE  statements or changes to individual rows caused by these ...
Triggers in SQL:1999 <ul><li>Consideration : Immediate </li></ul><ul><ul><li>Condition can refer to both the state of the ...
Trigger Syntax CREATE TRIGGER   name {BEFORE | AFTER} {INSERT | DELETE | UPDATE [OF  cols ]} ON  table [REFERENCING NEW AS...
Before Trigger Example (row granularity) CREATE TRIGGER   Max EnrollCheck BEFORE INSERT ON  Transcript REFERENCING NEW AS ...
After Trigger Example (row granularity) CREATE TRIGGER  LimitSalaryRaise AFTER UPDATE OF  Salary  ON  Employee REFERENCING...
After Trigger Example (statement granularity) CREATE TRIGGER  RecordNewAverage AFTER UPDATE OF  Salary  ON  Employee FOR E...
Stored Procedure
<ul><li>A function stored in the DB server </li></ul><ul><li>Can be invoked multiple times </li></ul><ul><li>Advantage: re...
Comparison Client Application DB2 Client Normal  Database Network DB Client Client Application DB2 Client Stored Procedure...
<ul><li>Allows local variables, loops, procedures, examination of one tuple at a time. </li></ul><ul><li>CREATE PROCEDURE ...
<ul><li>CREATE TABLE emp(id INTEGER, salary float);  </li></ul><ul><li>CREATE PROCEDURE  </li></ul><ul><li>UPDATE_EMP (IN ...
<ul><li>CALL UPDATE_EMP (2, 0.1);  </li></ul>Call Stored Procedures CALL UPDATE_EMP (3, 0.2);
<ul><li>Call another procedure in a procedure (like calling functions) </li></ul><ul><li>To call a target SQL procedure wi...
<ul><ul><li>CASE statement </li></ul></ul><ul><ul><li>FOR statement </li></ul></ul><ul><ul><li>GOTO statement </li></ul></...
<ul><li>Conditional Statements </li></ul><ul><ul><li>IF <condition> THEN </li></ul></ul><ul><ul><li><statement(s)> </li></...
<ul><li>  CREATE PROCEDURE UPDATE_SALARY_IF </li></ul><ul><li>(IN employee_number INT, IN rating SMALLINT) </li></ul><ul><...
Example 2 - This procedure receives a department number as an input parameter.  - A WHILE statement in the procedure body ...
<ul><li>CREATE PROCEDURE BUMP_SALARY_IF (IN deptnumber SMALLINT)  </li></ul><ul><li>LANGUAGE SQL  </li></ul><ul><li>BEGIN ...
<ul><li>OPEN C1; </li></ul><ul><li>FETCH C1 INTO v_id, v_salary, v_years; </li></ul><ul><li>WHILE at_end = 0 DO </li></ul>...
Other DBs - Different vendors could have implementations of stored procedures - Start from a sample program. Do not start ...
Embedded SQL
A Program to Access Databases  <ul><li>A program that includes SQL constructs. </li></ul><ul><li>SQL constructs can be inc...
Statement Level Interface <ul><li>SQL constructs in application take two forms: </li></ul><ul><ul><li>Standard SQL stateme...
Call Level Interface <ul><li>Application program written entirely in host language (no precompiler) </li></ul><ul><ul><li>...
Embedded SQL <ul><li>You can embed SQL statements into many programming languages    procedural power (loops, variables, ...
Static SQL <ul><li>Declaration section for host/SQL communication </li></ul><ul><li>Colon convention for value ( WHERE ) a...
Status EXEC  SQL  SELECT   C.NumEnrolled INTO   :num_enrolled FROM  Course C WHERE  C.CrsCode = :crs_code; if ( !strcmp ( ...
Cursor Overview <ul><li>Result set  - set of rows produced by a  SELECT  statement </li></ul><ul><li>Cursor  - pointer to ...
Cursor EXEC SQL DECLARE   GetEnroll  INSENSITIVE  CURSOR FOR SELECT   T.StudId, T.Grade FROM  Transcript T WHERE   T.CrsCo...
Cursor Types <ul><li>Insensitive cursor : Result set (effectively) computed and stored in a separate table at  OPEN  time ...
Insensitive Cursor key1 t t t t t t t t  key1  t t t t t t t t t  key3 yyyyyyyy  key2  xxxxxxxxx key4 zzzzzzzzz  key3  yyy...
Cursors DECLARE  cursor-name  [INSENSITIVE] [SCROLL]  CURSOR FOR   table-expression [ ORDER BY  column-list ] [ FOR {READ ...
Scrolling <ul><li>If  SCROLL  option not specified in  cursor declaration,  FETCH  always moves cursor forward one positio...
<ul><li>#include <stdio.h> </li></ul><ul><li>exec sql include sqlca; </li></ul><ul><li>int main() </li></ul><ul><li>{ </li...
ProC <ul><li>Each ESQL statement starts with EXEC SQL keyword and ends with a semicolon ; </li></ul><ul><li>A pre-compiler...
Program.pc Program.c
Variables in ESQL <ul><li>All variables that will be used in an SQL statement must be declared using an ESQL declaration a...
Executing SQL commands <ul><li>Suppose we want to find the name of an employee given his/her SSN (input by the user of the...
Dealing with Strings <ul><li>There is a mismatch between the definition of a string in Oracle and in C/C++.  </li></ul><ul...
More on strings <ul><li>Putting the pieces together: </li></ul><ul><li>strcpy(username.arr, “Zaki”) ; </li></ul><ul><li>us...
ESQL - Cursors <ul><li>When a select statement returns a set of tuples, then the tuples (rows) can only be retrieved one b...
ESQL – More Cursors <ul><li>More cursor operations </li></ul><ul><ul><li>open a cursor:  means the corresponding SQL query...
How do we know end of cursor? <ul><li>Each SQL statement executed in a program produces a status code that can be retrieve...
Transactions <ul><li>The most common ESQL statements are SELECT, INSERT INTO, and UPDATE statements. </li></ul><ul><li>A  ...
Dynamic SQL <ul><li>st is an SQL variable; names the SQL statement </li></ul><ul><li>tmp, crscode, num_enrolled are host l...
Dynamic SQL <ul><li>PREPARE  names SQL statement st and sends it to DBMS for preparation </li></ul><ul><li>EXECUTE  causes...
Dynamic SQL <ul><li>In Dynamic SQL, embedded SQL statements are created on the fly using strings! </li></ul><ul><ul><li>th...
SQLDA <ul><li>When we execute a dynamic SQL statement, we do not know which columns will be returned and how many columns ...
Descriptors temp = “ SELECT   C.NumEnrolled, C.Name  FROM  Course C WHERE  C.CrsCode = ‘CS305’ ” NumEnrolled integer Name ...
JDBC <ul><li>Call-level interface for executing SQL from a Java program </li></ul><ul><ul><li>Methods of object classes ar...
JDBC Organization DBMS application driver manager driver 3 driver 2 driver 1 DBMS
JDBC – Dynamic SQL <ul><li>Driver is a piece of software that enables communication between a program and a database syste...
Execute a Query Import  java.sql.*;  --import all classes in package java.sql Class.forName(“driver_name”);  --load specif...
Prepare and Execute a Query PreparedStatement ps = con.prepareStatement (“SQL statement”); -- Creates a prepared statement...
Result Sets and Cursors <ul><li>Three types of result sets: </li></ul><ul><ul><li>Forward-only: not scrollable </li></ul><...
Result Set <ul><li>Any result set type can be declared read-only or updatable  (assuming SQL query satisfies same conditio...
Handling Exceptions <ul><li>try/catch is the basic structure within which an SQL statement should be embedded </li></ul><u...
Transactions in JDBC <ul><li>Default  for a connection is  </li></ul><ul><ul><li>autocommit mode: each  SQL statement is a...
<ul><li>import java.sql.*; </li></ul><ul><li>import oracle.sql.*; </li></ul><ul><li>import oracle.jdbc.driver.*; </li></ul...
<ul><li>//  Create a statement which will return a cursor that will allow you to  </li></ul><ul><li>//  scroll the result ...
Upcoming SlideShare
Loading in...5
×

05027240 Database systems Database Application Development

612

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
612
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
19
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

05027240 Database systems Database Application Development

  1. 1. 05027240 Database systems Database Application Development Veera Boonjing [email_address] Semester 1/2547 King Mongkut’s Institute of Technology Ladkrabang
  2. 2. Triggers
  3. 3. Trigger Overview <ul><li>Element of the database schema </li></ul><ul><li>General form: ON < event > IF < condition > THEN < action > </li></ul><ul><ul><li>Event - request to execute database operation </li></ul></ul><ul><ul><li>Condition - predicate evaluated on database state </li></ul></ul><ul><ul><li>Action – execution of procedure that might involve database updates </li></ul></ul><ul><li>Example: ON updating maximum course enrollment IF number registered > new max enrollment limit THEN deregister students using LIFO policy </li></ul>
  4. 4. Trigger Details <ul><li>Activation - Occurrence of the event </li></ul><ul><li>Consideration - The point, after activation, when condition is evaluated </li></ul><ul><ul><li>Immediate or deferred (when the transaction requests to commit) </li></ul></ul><ul><ul><li>Condition might refer to both the state before and the state after event occurs </li></ul></ul>
  5. 5. Trigger Details <ul><li>Execution - point at which action occurs </li></ul><ul><ul><li>With deferred consideration, execution is also deferred </li></ul></ul><ul><ul><li>With immediate consideration, execution can occur immediately after consideration or it can be deferred </li></ul></ul><ul><ul><ul><li>If execution is immediate, execution can occur before, after, or instead of triggering event. </li></ul></ul></ul><ul><ul><ul><li>Before triggers adapt naturally to maintaining integrity constraints: violation results in rejection of event. </li></ul></ul></ul>
  6. 6. Trigger Details <ul><li>Granularity - </li></ul><ul><ul><li>Row-level granularity: change of a single row is an event (a single UPDATE statement might result in multiple events) </li></ul></ul><ul><ul><li>Statement-level granularity: events are statements (a single UPDATE statement that changes multiple rows is a single event). </li></ul></ul>
  7. 7. Trigger Details <ul><li>Multiple Triggers </li></ul><ul><ul><li>How should multiple triggers activated by a single event be handled? </li></ul></ul><ul><ul><ul><li>Evaluate one condition at a time and if true immediately execute action or </li></ul></ul></ul><ul><ul><ul><li>Evaluate all conditions , then execute actions </li></ul></ul></ul><ul><ul><li>The execution of an action can affect the truth of a subsequently evaluated condition so the choice is significant. </li></ul></ul>
  8. 8. Triggers in SQL/3 <ul><li>Events : INSERT, DELETE , or UPDATE statements or changes to individual rows caused by these statements </li></ul><ul><li>Condition : Anything allowed in a WHERE clause </li></ul><ul><ul><li>No subqueries in Oracle </li></ul></ul><ul><li>Action : An individual SQL statement or a program written in the language of Procedural Stored Modules (PSM) (which can contain embedded SQL statements) </li></ul>
  9. 9. Triggers in SQL:1999 <ul><li>Consideration : Immediate </li></ul><ul><ul><li>Condition can refer to both the state of the affected row or table before and after the event occurs </li></ul></ul><ul><li>Execution : Immediate - can be before or after the execution of triggering event . </li></ul><ul><ul><li>Action of before trigger cannot modify the database </li></ul></ul><ul><li>Granularity : Both row-level and statement-level granularity </li></ul>
  10. 10. Trigger Syntax CREATE TRIGGER name {BEFORE | AFTER} {INSERT | DELETE | UPDATE [OF cols ]} ON table [REFERENCING NEW AS var | REFERENCING OLD AS var | REFERENCING NEW TABLE AS var | REFERENCING OLD TABLE AS var ] [FOR EACH {ROW | STATEMENT}] [WHEN ( cond) ] statements New/Old (Table) refers only to the tuple(s) affected by the event
  11. 11. Before Trigger Example (row granularity) CREATE TRIGGER Max EnrollCheck BEFORE INSERT ON Transcript REFERENCING NEW AS N -- row to be added FOR EACH ROW WHEN ((SELECT COUNT (T.StudId) FROM Transcript T WHERE T.CrsCode = N.CrsCode AND T.Semester = N.Semester) >= ( SELECT C.MaxEnroll FROM Course C WHERE C.CrsCode = N.CrsCode )) ABORT TRANSACTION
  12. 12. After Trigger Example (row granularity) CREATE TRIGGER LimitSalaryRaise AFTER UPDATE OF Salary ON Employee REFERENCING OLD AS O NEW AS N FOR EACH ROW WHEN (N.salary - O.Salary > 0.05 * O.Salary) UPDATE Employee -- action SET Salary = 1.05 * O.Salary WHERE Id = O.Id Note: The action itself is a triggering event (but in this case a chain reaction is not possible)
  13. 13. After Trigger Example (statement granularity) CREATE TRIGGER RecordNewAverage AFTER UPDATE OF Salary ON Employee FOR EACH STATEMENT INSERT INTO Log VALUES (CURRENT_DATE, SELECT AVG (Salary) FROM Employee)
  14. 14. Stored Procedure
  15. 15. <ul><li>A function stored in the DB server </li></ul><ul><li>Can be invoked multiple times </li></ul><ul><li>Advantage: reduce network traffic </li></ul><ul><li>Can also be written using other languages (e.g., C, Java) </li></ul><ul><li>Different vendors could have different implementations </li></ul><ul><ul><li>Check the manual and sample programs </li></ul></ul>Stored Procedure Overview
  16. 16. Comparison Client Application DB2 Client Normal Database Network DB Client Client Application DB2 Client Stored Procedure Applications using stored procedures Network DB Client DB Server DB2 DB Server DB2
  17. 17. <ul><li>Allows local variables, loops, procedures, examination of one tuple at a time. </li></ul><ul><li>CREATE PROCEDURE <name> (<arglist>) </li></ul><ul><li>BEGIN </li></ul><ul><ul><ul><li><procedure statements> </li></ul></ul></ul><ul><ul><ul><li>END </li></ul></ul></ul><ul><ul><ul><li>@ </li></ul></ul></ul><ul><li><Procedure Statements> can have multiple SQL statements </li></ul><ul><li>'@' needed for ending and running. </li></ul><ul><li>Each argument can be: </li></ul><ul><ul><li>IN </li></ul></ul><ul><ul><li>OUT </li></ul></ul><ul><ul><li>IN OUT </li></ul></ul>Declare Stored Procedures (NetDB2)
  18. 18. <ul><li>CREATE TABLE emp(id INTEGER, salary float); </li></ul><ul><li>CREATE PROCEDURE </li></ul><ul><li>UPDATE_EMP (IN idNum INTEGER, IN rate FLOAT) </li></ul><ul><li>LANGUAGE SQL </li></ul><ul><li>BEGIN </li></ul><ul><li>UPDATE EMP </li></ul><ul><li>SET salary = salary* (1.0 + rate) </li></ul><ul><li>WHERE id = idNum; </li></ul><ul><li>END </li></ul><ul><li>@ </li></ul><ul><li>Name: UPDATE_EMP. </li></ul><ul><li>The two parameters are of data type INTEGER and FLOAT. Both are input parameters. </li></ul><ul><li>LANGUAGE SQL indicates that this is an SQL procedure, so a procedure body follows the other parameters. </li></ul><ul><li>The procedure body consists of a single SQL UPDATE statement, which updates rows in the emp table. </li></ul><ul><li>'@' is used as the terminating character for stored procedures in NetDB2. </li></ul>Example
  19. 19. <ul><li>CALL UPDATE_EMP (2, 0.1); </li></ul>Call Stored Procedures CALL UPDATE_EMP (3, 0.2);
  20. 20. <ul><li>Call another procedure in a procedure (like calling functions) </li></ul><ul><li>To call a target SQL procedure within a caller SQL procedure, simply include a CALL statement with the appropriate number and types of parameters. </li></ul><ul><li>CREATE PROCEDURE NEST_SALES(OUT budget DECIMAL(11,2)) </li></ul><ul><li>LANGUAGE SQL </li></ul><ul><li>BEGIN </li></ul><ul><li>DECLARE total INTEGER DEFAULT 0; </li></ul><ul><li>SET total = 6; </li></ul><ul><li>CALL SALES_TARGET(total);  call another procedure </li></ul><ul><li>SET budget = total * 10000; </li></ul><ul><li>END </li></ul><ul><li>@ </li></ul><ul><li>“ budget” is an output variable </li></ul>Nested Procedures
  21. 21. <ul><ul><li>CASE statement </li></ul></ul><ul><ul><li>FOR statement </li></ul></ul><ul><ul><li>GOTO statement </li></ul></ul><ul><ul><li>IF statement </li></ul></ul><ul><ul><li>ITERATE statement </li></ul></ul><ul><ul><li>RETURN statement </li></ul></ul><ul><ul><li>WHILE statement </li></ul></ul><ul><li>Similar to other programming languages. </li></ul>Valid Body Statements
  22. 22. <ul><li>Conditional Statements </li></ul><ul><ul><li>IF <condition> THEN </li></ul></ul><ul><ul><li><statement(s)> </li></ul></ul><ul><ul><li>ELSE </li></ul></ul><ul><ul><li><statement(s)> </li></ul></ul><ul><ul><li>END IF; </li></ul></ul><ul><li>Loops </li></ul><ul><ul><li>LOOP </li></ul></ul><ul><ul><li>…… </li></ul></ul><ul><ul><li>EXIT WHEN <condition> </li></ul></ul><ul><ul><li>…… </li></ul></ul><ul><ul><li>END LOOP; </li></ul></ul>Example Statements
  23. 23. <ul><li> CREATE PROCEDURE UPDATE_SALARY_IF </li></ul><ul><li>(IN employee_number INT, IN rating SMALLINT) </li></ul><ul><li>LANGUAGE SQL </li></ul><ul><li>BEGIN </li></ul><ul><li> IF (rating = 1) THEN </li></ul><ul><ul><ul><li>BEGIN </li></ul></ul></ul><ul><ul><ul><li> DECLARE count INT; </li></ul></ul></ul><ul><li> SET counter = 10; </li></ul><ul><li> WHILE (counter > 0) DO </li></ul><ul><li>UPDATE employee </li></ul><ul><li>SET salary = salary * 1.10, bonus = 1000 </li></ul><ul><li>WHERE empno = COUNT; </li></ul><ul><li> SET counter = counter – 1; </li></ul><ul><li>END WHILE; </li></ul><ul><li> END </li></ul><ul><li>ELSEIF (rating = 2) </li></ul><ul><li>THEN UPDATE employee </li></ul><ul><li>SET salary = salary * 1.05, bonus = 500 </li></ul><ul><li>WHERE empno = employee_number; </li></ul><ul><li>ELSE UPDATE employee </li></ul><ul><li>SET salary = salary * 1.03, bonus = 0 </li></ul><ul><li>WHERE empno = employee_number; </li></ul><ul><li>END IF; </li></ul><ul><li>END </li></ul><ul><li>@ </li></ul>Example 1
  24. 24. Example 2 - This procedure receives a department number as an input parameter. - A WHILE statement in the procedure body fetches the salary and bonus for each employee in the department. - An IF statement within the WHILE statement updates salaries for each employee, depending on number of years of service and current salary. - When all employee records in the department have been processed, the FETCH statement that retrieves employee records receives SQLSTATE 20000. - A not_found condition handler makes the search condition for the WHILE statement false, so execution of the WHILE statement ends
  25. 25. <ul><li>CREATE PROCEDURE BUMP_SALARY_IF (IN deptnumber SMALLINT) </li></ul><ul><li>LANGUAGE SQL </li></ul><ul><li>BEGIN </li></ul><ul><li>DECLARE v_salary DOUBLE; </li></ul><ul><li>DECLARE v_years SMALLINT; </li></ul><ul><li>DECLARE v_id SMALLINT; </li></ul><ul><li>DECLARE at_end INT DEFAULT 0; </li></ul><ul><li>DECLARE not_found CONDITION FOR SQLSTATE '02000';  “not found” reached </li></ul><ul><li>-- CAST salary as DOUBLE because SQL procedures do not support DECIMAL </li></ul><ul><li>DECLARE C1 CURSOR FOR </li></ul><ul><li>SELECT id, CAST(salary AS DOUBLE), years </li></ul><ul><li>FROM staff; </li></ul><ul><li>DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1; </li></ul>
  26. 26. <ul><li>OPEN C1; </li></ul><ul><li>FETCH C1 INTO v_id, v_salary, v_years; </li></ul><ul><li>WHILE at_end = 0 DO </li></ul><ul><li>IF (v_salary < 2000 * v_years) </li></ul><ul><li>THEN UPDATE staff </li></ul><ul><li>SET salary = 2150 * v_years </li></ul><ul><li>WHERE id = v_id; </li></ul><ul><li>ELSEIF (v_salary < 5000 * v_years) </li></ul><ul><li>THEN IF (v_salary < 3000 * v_years) </li></ul><ul><li>THEN UPDATE staff </li></ul><ul><li>SET salary = 3000 * v_years </li></ul><ul><li>WHERE id = v_id; </li></ul><ul><li>ELSE UPDATE staff </li></ul><ul><li>SET salary = v_salary * 1.10 </li></ul><ul><li>WHERE id = v_id; </li></ul><ul><li>END IF; </li></ul><ul><li>ELSE UPDATE staff </li></ul><ul><li>SET job = 'PREZ' </li></ul><ul><li>WHERE id = v_id; </li></ul><ul><li>END IF; </li></ul><ul><li>FETCH C1 INTO v_id, v_salary, v_years; </li></ul><ul><li>END WHILE; </li></ul><ul><li>CLOSE C1; </li></ul><ul><li>END </li></ul>
  27. 27. Other DBs - Different vendors could have implementations of stored procedures - Start from a sample program. Do not start from scratch! - “Cut and paste”
  28. 28. Embedded SQL
  29. 29. A Program to Access Databases <ul><li>A program that includes SQL constructs. </li></ul><ul><li>SQL constructs can be included in a program in two different ways: </li></ul><ul><ul><li>Statement Level Interface </li></ul></ul><ul><ul><li>Call Level Interface </li></ul></ul>
  30. 30. Statement Level Interface <ul><li>SQL constructs in application take two forms: </li></ul><ul><ul><li>Standard SQL statements ( static or embedded SQL): Useful when SQL portion of program is known at compile time </li></ul></ul><ul><ul><li>Directives ( dynamic SQL): Useful when SQL portion of program not known at compile time. Application constructs SQL statements at run time as values of host language variables that are manipulated by directives </li></ul></ul><ul><li>Precompiler translates statements and directives into arguments of calls to library procedures. </li></ul>
  31. 31. Call Level Interface <ul><li>Application program written entirely in host language (no precompiler) </li></ul><ul><ul><li>Examples: JDBC, ODBC </li></ul></ul><ul><li>SQL statements are values of string variables constructed at run time using host language </li></ul><ul><ul><li>As with dynamic SQL </li></ul></ul><ul><li>Application uses strings as arguments of library routines that communicate with DBMS </li></ul><ul><ul><li>e.g. executeQuery(“SQL query statement”) </li></ul></ul>
  32. 32. Embedded SQL <ul><li>You can embed SQL statements into many programming languages  procedural power (loops, variables, etc.) </li></ul><ul><li>The main components of embedded SQL programming: </li></ul><ul><ul><li>Regular program blocks </li></ul></ul><ul><ul><li>SQL code </li></ul></ul><ul><ul><li>Methods to connect to the database, invoke the SQL code and retrieve results </li></ul></ul><ul><ul><li>Methods to pass data from program variables to the SQL code </li></ul></ul><ul><ul><li>Methods to retrieve data from the result of queries to program variables </li></ul></ul>
  33. 33. Static SQL <ul><li>Declaration section for host/SQL communication </li></ul><ul><li>Colon convention for value ( WHERE ) and result ( INTO ) parameters </li></ul>EXEC SQL BEGIN DECLARE SECTION ; unsigned long num_enrolled; char crs_code; char SQLSTATE [6]; EXEC SQL END DECLARE SECTION ; ……… . EXEC SQL SELECT C.NumEnrolled INTO :num_enrolled FROM Course C WHERE C.CrsCode = :crs_code;
  34. 34. Status EXEC SQL SELECT C.NumEnrolled INTO :num_enrolled FROM Course C WHERE C.CrsCode = :crs_code; if ( !strcmp ( SQLSTATE, “00000”) ) { printf ( “statement failed” ) };
  35. 35. Cursor Overview <ul><li>Result set - set of rows produced by a SELECT statement </li></ul><ul><li>Cursor - pointer to a row in the result set. </li></ul><ul><li>Cursor operations: </li></ul><ul><ul><li>Declaration </li></ul></ul><ul><ul><li>Open - execute SELECT to determine result set and initialize pointer </li></ul></ul><ul><ul><li>Fetch - advance pointer and retrieve next row </li></ul></ul><ul><ul><li>Close - deallocate cursor </li></ul></ul>
  36. 36. Cursor EXEC SQL DECLARE GetEnroll INSENSITIVE CURSOR FOR SELECT T.StudId, T.Grade FROM Transcript T WHERE T.CrsCode = :crscode AND T.Semester = ‘S2000’; ……… EXEC SQL OPEN GetEnroll; if ( !strcmp ( SQLSTATE , “00000”)) {... fail exit... }; ……… . EXEC SQL FETCH GetEnroll INTO :studid, :grade; while ( SQLSTATE = “00000”) { … process the returned row...; EXEC SQL FETCH GetEnroll INTO :studid, :grade; } if ( !strcmp ( SQLSTATE , “02000”)) {... fail exit... }; ……… . EXEC SQL CLOSE GetEnroll;
  37. 37. Cursor Types <ul><li>Insensitive cursor : Result set (effectively) computed and stored in a separate table at OPEN time </li></ul><ul><ul><li>Changes made to base table subsequent to OPEN (by any transaction) do not affect result set </li></ul></ul><ul><ul><li>Cursor is read-only </li></ul></ul><ul><li>Cursors that are not insensitive : Specification not part of SQL standard </li></ul><ul><ul><li>Changes made to base table subsequent to OPEN (by any transaction) can affect result set </li></ul></ul><ul><ul><li>Cursor is updatable </li></ul></ul>
  38. 38. Insensitive Cursor key1 t t t t t t t t key1 t t t t t t t t t key3 yyyyyyyy key2 xxxxxxxxx key4 zzzzzzzzz key3 yyyyyyyyy key4 zzzzzzzzzz key5 uuuuuuuuu key6 vvvvvvvvv Cursor Result Set Base Table
  39. 39. Cursors DECLARE cursor-name [INSENSITIVE] [SCROLL] CURSOR FOR table-expression [ ORDER BY column-list ] [ FOR {READ ONLY | UPDATE [ OF column-list ] } ] For updatable (not insensitive, not read-only) cursors UPDATE table-name --base table SET assignment WHERE CURRENT OF cursor-name DELETE FROM table-name --base table WHERE CURRENT OF cursor-name
  40. 40. Scrolling <ul><li>If SCROLL option not specified in cursor declaration, FETCH always moves cursor forward one position </li></ul><ul><li>If SCROLL option is included, cursor can be moved in arbitrary ways around result set </li></ul>FETCH PRIOR FROM GetEnroll INTO :studid, :grade; • Also FIRST, LAST, ABSOLUTE n , RELATIVE n
  41. 41. <ul><li>#include <stdio.h> </li></ul><ul><li>exec sql include sqlca; </li></ul><ul><li>int main() </li></ul><ul><li>{ </li></ul><ul><li>exec sql begin declare section; /* declare SQL host variables */ </li></ul><ul><li>char cust_id[5]; </li></ul><ul><li>char cust_name[14]; </li></ul><ul><li>float cust_discnt; /* host var for discnt value */ </li></ul><ul><li>char user_name[20], user_pwd[20]; </li></ul><ul><li>exec sql end declare section; </li></ul><ul><li>exec sql whenever sqlerror goto report_error; /* error trap condition */ </li></ul><ul><li>exec sql whenever not found goto notfound; /* not found condition */ </li></ul><ul><li>/*C code for reading user_name and user_pwd */ </li></ul><ul><li>exec sql connect :user_name </li></ul><ul><li>identified by :user_pwd; /* ORACLE format: connect */ </li></ul><ul><li>while (true) { </li></ul><ul><li>/* C code for reading customer id from stdin */ </li></ul><ul><li>exec sql select cname, </li></ul><ul><li>discnt into :cust_name, :cust_discnt /* retrieve cname, discnt */ </li></ul><ul><li>from customers where cid = :cust_id; </li></ul><ul><li>exec sql commit work; /* release read lock on row */ </li></ul><ul><li>printf(&quot;CUSTOMER'S NAME IS %s AND DISCNT IS %5.1f &quot;, </li></ul><ul><li>cust_name, cust_discnt); /* NOTE, (:) not used here */ </li></ul><ul><li>continue; </li></ul>
  42. 42. ProC <ul><li>Each ESQL statement starts with EXEC SQL keyword and ends with a semicolon ; </li></ul><ul><li>A pre-compiler will scan a program file and only read the statements enclosed within EXEC SQL statements and disregard everything else. </li></ul><ul><li>SQLCA is a specific data structure for storing status codes of all SQL operations </li></ul><ul><li>/* always have this for error handling*/ </li></ul><ul><li>exec sql include sqlca ; </li></ul>
  43. 43. Program.pc Program.c
  44. 44. Variables in ESQL <ul><li>All variables that will be used in an SQL statement must be declared using an ESQL declaration and data type </li></ul><ul><li>exec sql begin declare section ; </li></ul><ul><li>VARCHAR e_name[30], username[30], passwd[30] ; </li></ul><ul><li>INTEGER e_ssn, e_dept_id ; </li></ul><ul><li>exec sql end declare section ; </li></ul><ul><li>You can use almost any SQL command in ESQL as long as proper input to these commands are provided in the form of program variables. </li></ul><ul><li>To execute any command, you must first connect to a database in which all your tables reside. </li></ul><ul><li>exec sql connect :username identified by :passwd ; </li></ul>
  45. 45. Executing SQL commands <ul><li>Suppose we want to find the name of an employee given his/her SSN (input by the user of the program): </li></ul><ul><li>exec sql select name, dept_id into :e_name, :e_dept_id </li></ul><ul><li>from employee </li></ul><ul><li>where ssn = :e_ssn ; </li></ul><ul><li>Read the value of the variable “e_ssn” and execute the SQL statement using this value, store the returned values of columns “name” and “dept_id” in the program variables “e_name” and “e_dept_id”. </li></ul><ul><li>Compare the above query with the expression below. What is the difference? </li></ul><ul><li>exec sql select name, dept_id </li></ul><ul><li> from employee where ssn = e_ssn ; </li></ul>Program variables are preceded by “:”
  46. 46. Dealing with Strings <ul><li>There is a mismatch between the definition of a string in Oracle and in C/C++. </li></ul><ul><ul><li>In C, the end of a string is identified by the null character ‘’. Hence, “Zaki” would be stored as characters ‘Z’,’a’,’k’,’i’,’’. </li></ul></ul><ul><ul><li>In Oracle, the length of a string is stored together with the string and there is no special end of string character. </li></ul></ul><ul><ul><li>If you convert a data string from Oracle to C, you must pad it with ‘’ manually! </li></ul></ul><ul><li>The data type VARCHAR e_name[30] is translated by the pre-compiler to the following structure: </li></ul><ul><ul><li>struct { </li></ul></ul><ul><ul><li>unsigned short len </li></ul></ul><ul><ul><li>unsigned char arr[30] </li></ul></ul><ul><ul><li>} e_name ; </li></ul></ul>
  47. 47. More on strings <ul><li>Putting the pieces together: </li></ul><ul><li>strcpy(username.arr, “Zaki”) ; </li></ul><ul><li>username.len = strlen(“Zaki”) ; </li></ul><ul><li>strcpy(passwd.arr, “tweety-bird”) ; </li></ul><ul><li>passwd.len = strlen(“tweety-bird”) ; </li></ul><ul><li>exec sql connect :username identified by :passwd ; </li></ul><ul><li>scanf(“%d”, &e_ssn) ; </li></ul><ul><li>exec sql select name, dept_id into :e_name, :e_dept_id </li></ul><ul><li>from employee where ssn = :e_ssn ; </li></ul><ul><li>e_name.arr[e_name.len] = ‘’ ; /* so can use string in C*/ </li></ul><ul><li>printf(“%s”, e_name.arr) ; </li></ul><ul><li>exec sql commit work ; /* make any changes permanent */ </li></ul><ul><li>exec sql disconnect ; /* disconnect from the database */ </li></ul>
  48. 48. ESQL - Cursors <ul><li>When a select statement returns a set of tuples, then the tuples (rows) can only be retrieved one by one. </li></ul><ul><ul><li>programming language variables can contain only one value at a time </li></ul></ul><ul><ul><li>this is sometimes called an impedance mismatch </li></ul></ul><ul><li>Cursor operations </li></ul><ul><ul><li>declare a cursor using a regular SQL query (no “into”). </li></ul></ul><ul><ul><li>exec sql declare emps_dept cursor for </li></ul></ul><ul><ul><li>select ssn, name from employee </li></ul></ul><ul><ul><li>where dept_id = :e_dept_id ; </li></ul></ul>
  49. 49. ESQL – More Cursors <ul><li>More cursor operations </li></ul><ul><ul><li>open a cursor: means the corresponding SQL query is executed, the results are written to a file (or a data structure) and the cursor is pointing to the first row. </li></ul></ul><ul><ul><li>exec sql open emps_dept ; </li></ul></ul><ul><ul><li>read the current row pointed to by the cursor using “fetch”. At the end of fetch, the cursor is moved to point to the next tuple. </li></ul></ul><ul><ul><li>exec sql fetch emps_dept into :e_ssn, :e_name ; </li></ul></ul>
  50. 50. How do we know end of cursor? <ul><li>Each SQL statement executed in a program produces a status code that can be retrieved from the SQL Communication Area (SQLCA) variables. </li></ul><ul><li>Check the “sqlcode” to see if the end of a cursor is reached (expected value depends on the system). </li></ul><ul><ul><li>if (sqlca.sqlcode == -1) { … } </li></ul></ul><ul><li>Error handling statements </li></ul><ul><ul><li>exec sql whenever sqlerror </li></ul></ul><ul><ul><li>{continue, stop, goto label, call function} </li></ul></ul><ul><ul><li>exec sql whenever is a trap condition, it hold for all exec sql statements unless a new trap condition overrides the current one. </li></ul></ul>
  51. 51. Transactions <ul><li>The most common ESQL statements are SELECT, INSERT INTO, and UPDATE statements. </li></ul><ul><li>A transaction in a program starts with the first read or write to a database (not with connect) and ends when either one of the following commands is executed </li></ul><ul><ul><li>exec sql commit work ; </li></ul></ul><ul><ul><li>/* changes to the database are made permanent */ </li></ul></ul><ul><ul><li>exec sql rollback work ; </li></ul></ul><ul><ul><li>/* restore all tuples to their original values */ </li></ul></ul><ul><li>If a program did not complete correctly, then changes can be undone to restore a consistent state. </li></ul>
  52. 52. Dynamic SQL <ul><li>st is an SQL variable; names the SQL statement </li></ul><ul><li>tmp, crscode, num_enrolled are host language variables (note colon notation) </li></ul><ul><li>crscode is an in parameter, supplies value for placemarker (?) </li></ul><ul><li>num_enrolled is an out parameter, receives value from C.NumEnrolled </li></ul>Strcpy (tmp, “ SELECT C.NumEnrolled FROM Course C WHERE C.CrsCode = ?”) ; EXEC SQL PREPARE st FROM :tmp ; EXEC SQL EXECUTE st INTO :num_enrolled USING :crs_code;
  53. 53. Dynamic SQL <ul><li>PREPARE names SQL statement st and sends it to DBMS for preparation </li></ul><ul><li>EXECUTE causes the statement named st to be executed </li></ul>
  54. 54. Dynamic SQL <ul><li>In Dynamic SQL, embedded SQL statements are created on the fly using strings! </li></ul><ul><ul><li>these strings are fed to an exec sql statement </li></ul></ul><ul><ul><li>exec sql execute immediate :sql_string </li></ul></ul><ul><li>Dynamic SQL statements are not known to pre-compiler at compile time; they must be optimized at run time! </li></ul><ul><li>Create a query once using a prepare statement and run it multiple times using the execute statement. </li></ul><ul><ul><ul><li>strcpy(sqltext.arr, “delete from employee </li></ul></ul></ul><ul><ul><ul><li>where ssn = ?”) ; </li></ul></ul></ul><ul><ul><ul><li>sqltext.len=str.len(sqltext.arr) ; </li></ul></ul></ul><ul><ul><ul><li>exec sql prepare del_emp from :sqltext ; </li></ul></ul></ul><ul><ul><ul><li>exec sql execute del_emp using :cust_id ; </li></ul></ul></ul>
  55. 55. SQLDA <ul><li>When we execute a dynamic SQL statement, we do not know which columns will be returned and how many columns will be returned. </li></ul><ul><li>The SQLDA descriptor definition allows us to find the number of columns and the value for each column. </li></ul><ul><ul><li>exec sql include sqlda ; </li></ul></ul><ul><ul><li>exec sql declare sel_curs cursor for sel_emps ; </li></ul></ul><ul><ul><li>exec sql prepare sel_emps from :sqltext ; </li></ul></ul><ul><ul><li>exec sql describe sel_emps into sqlda ; </li></ul></ul><ul><ul><li>exec sql open sel_curs ; </li></ul></ul><ul><ul><li>exec sql fetch sel_curs using descriptor sqlda ; </li></ul></ul>
  56. 56. Descriptors temp = “ SELECT C.NumEnrolled, C.Name FROM Course C WHERE C.CrsCode = ‘CS305’ ” NumEnrolled integer Name string desc DBMS application GET DESCRIPTOR 1. Application fetches name, type 2. Then gets value into appropriate host variable 3. Then displays name and value. Value name type
  57. 57. JDBC <ul><li>Call-level interface for executing SQL from a Java program </li></ul><ul><ul><li>Methods of object classes are procedures of CLI </li></ul></ul><ul><li>SQL statement constructed at run time as the value of a Java variable (as in dynamic SQL) </li></ul><ul><li>JDBC dialect of SQL can be interfaced to any DBMS (driver does the translation) </li></ul>
  58. 58. JDBC Organization DBMS application driver manager driver 3 driver 2 driver 1 DBMS
  59. 59. JDBC – Dynamic SQL <ul><li>Driver is a piece of software that enables communication between a program and a database system (DMBS specific packages). </li></ul><ul><li>It implements a number of main classes: </li></ul><ul><ul><li>Connection (opening, closing, committing) </li></ul></ul><ul><ul><li>Statement (executing queries) </li></ul></ul><ul><ul><li>Result set (going through cursors, extracting information) </li></ul></ul>
  60. 60. Execute a Query Import java.sql.*; --import all classes in package java.sql Class.forName(“driver_name”); --load specified driver Connection con = DriverManager.getConnection (..url, userId, PW..); -- Attempts to connect to DBMS -- If successful creates a connection object, con, for managing connection Statement stat = con.CreateStatement (); -- Creates a statement object stat ResultSet res = stat.executeQuery (“SQL query statement”); -- Creates a result set object and stores the result set produced by execution of the argument query in it
  61. 61. Prepare and Execute a Query PreparedStatement ps = con.prepareStatement (“SQL statement”); -- Creates a prepared statement object ps containing the prepared SQL statement -- Placeholders (?) used to denote in parameters ps.setInt(1, i); -- set value of first in parameter to value of i ResultSet res = ps.executeQuery ( ); -- Creates a result set object and stores the result set produced by execution of the argument query in it while (res.next () ) { j = res.getInt ( …attribute name…); ……… } -- fetch output values
  62. 62. Result Sets and Cursors <ul><li>Three types of result sets: </li></ul><ul><ul><li>Forward-only: not scrollable </li></ul></ul><ul><ul><li>Scroll-insensitive: scrollable, changes made to underlying tables subsequent to result set computation not visible through result set </li></ul></ul><ul><ul><li>Scroll-sensitive: scrollable, changes made to underlying tables subsequent to result set computation are visible through result set </li></ul></ul>
  63. 63. Result Set <ul><li>Any result set type can be declared read-only or updatable (assuming SQL query satisfies same conditions as an updatable view) </li></ul><ul><li>Once an updatable result set has been computed, its current row can be updated or deleted, and a new row can be inserted, causing changes in base table </li></ul>Statement stat = con.createStatement ( resultSet.TYPE_SCROLL_SENSITIVE, resultSet.CONCUR_UPDATABLE ); res.updateString (“Name”, “John” ); --update attribute “Name”. res.updateRow ( ); --install update in res and underlying table.
  64. 64. Handling Exceptions <ul><li>try/catch is the basic structure within which an SQL statement should be embedded </li></ul><ul><li>If an exception is thrown, an exception object is created and the catch clause is executed </li></ul><ul><li>The exception object has methods to print an error message, return SQLSTATE , etc. </li></ul>try {...Java/JDBC code...} catch ( SQLException ex { handle exception } )
  65. 65. Transactions in JDBC <ul><li>Default for a connection is </li></ul><ul><ul><li>autocommit mode: each SQL statement is a transaction. </li></ul></ul><ul><ul><ul><li>To group statements use con.setautocommit (false) </li></ul></ul></ul><ul><ul><li>default isolation level of DBMS </li></ul></ul><ul><ul><ul><li>To change isolation level use </li></ul></ul></ul><ul><li>Transaction on connection con is committed using con.commit. Next transaction automatically initiated (chaining) </li></ul><ul><li>Transactions on each connection committed separately </li></ul><ul><ul><ul><li>con.setTransactionIsolationLevel(TRANSACTION_SERIALIZABLE ) </li></ul></ul></ul>
  66. 66. <ul><li>import java.sql.*; </li></ul><ul><li>import oracle.sql.*; </li></ul><ul><li>import oracle.jdbc.driver.*; </li></ul><ul><li>class Employee </li></ul><ul><li>{ </li></ul><ul><li>public static void main (String args []) throws SQLException </li></ul><ul><li>{//Set your user name and the password </li></ul><ul><li>String userName = &quot;dummy&quot; ; </li></ul><ul><li>String passWord = &quot;dummy&quot; ; </li></ul><ul><li>// Load the Oracle JDBC driver </li></ul><ul><li>DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); </li></ul><ul><li>Connection conn = DriverManager.getConnection </li></ul><ul><li> (&quot;jdbc:oracle:thin:@vcmr57.server.rpi.edu:1521:ora8&quot;, </li></ul><ul><li>userName,passWord); </li></ul>
  67. 67. <ul><li>// Create a statement which will return a cursor that will allow you to </li></ul><ul><li>// scroll the result set using both &quot;next&quot; and &quot;previous&quot; methods </li></ul><ul><li>Statement stmt = conn.createStatement </li></ul><ul><li>(ResultSet.TYPE_SCROLL_INSENSITIVE, </li></ul><ul><li> ResultSet.CONCUR_READ_ONLY); </li></ul><ul><li>ResultSet rset = stmt.executeQuery </li></ul><ul><li>(&quot;SELECT name, oid FROM items &quot;); </li></ul><ul><li>// Iterate through the result and print the item names </li></ul><ul><li>while (rset.next ()) { </li></ul><ul><li>//Get item name, which is the first column </li></ul><ul><li>System.out.println ( rset.getString (1) ); </li></ul><ul><li>PreparedStatement pstmt = conn.prepareStatement </li></ul><ul><li>(&quot;SELECT name FROM owners WHERE oid = ?&quot;) ; </li></ul><ul><li>//Feed owner id retrieved from rset into pstmt </li></ul><ul><li>pstmt.setInt(1, rset.getInt (2)); </li></ul><ul><li> ResultSet dset = pstmt.executeQuery() ; </li></ul><ul><li>if (dset.next()) </li></ul><ul><li>System.out.println(dset.getString (1)); </li></ul><ul><li>} } } </li></ul>
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×