67
1 05027240 Database systems Database Application Development Veera Boonjing [email protected] Semester 1/2547 King Mongkut’s Institute of Technology Ladkrabang

05027240 Database systems Database Application Development

  • Upload
    tess98

  • View
    602

  • Download
    2

Embed Size (px)

Citation preview

Page 1: 05027240 Database systems Database Application Development

1

05027240 Database systems

Database Application Development

Veera [email protected]

Semester 1/2547

King Mongkut’s Institute of Technology Ladkrabang

Page 2: 05027240 Database systems Database Application Development

2

Triggers

Page 3: 05027240 Database systems Database Application Development

3

Trigger Overview• Element of the database schema• General form:

ON <event> IF <condition> THEN <action>– Event- request to execute database operation

– Condition - predicate evaluated on database state

– Action – execution of procedure that might involve database updates

• Example: ON updating maximum course enrollment

IF number registered > new max enrollment limit THEN deregister students using LIFO policy

Page 4: 05027240 Database systems Database Application Development

4

Trigger Details

• Activation - Occurrence of the event

• Consideration - The point, after activation, when condition is evaluated– Immediate or deferred (when the transaction

requests to commit)– Condition might refer to both the state before

and the state after event occurs

Page 5: 05027240 Database systems Database Application Development

5

Trigger Details

• Execution - point at which action occurs– With deferred consideration, execution is also

deferred– With immediate consideration, execution can

occur immediately after consideration or it can be deferred

• If execution is immediate, execution can occur before, after, or instead of triggering event.

• Before triggers adapt naturally to maintaining integrity constraints: violation results in rejection of event.

Page 6: 05027240 Database systems Database Application Development

6

Trigger Details

• Granularity - – Row-level granularity: change of a single row

is an event (a single UPDATE statement might result in multiple events)

– Statement-level granularity: events are statements (a single UPDATE statement that changes multiple rows is a single event).

Page 7: 05027240 Database systems Database Application Development

7

Trigger Details

• Multiple Triggers – How should multiple triggers activated by a

single event be handled?• Evaluate one condition at a time and if true

immediately execute action or• Evaluate all conditions, then execute actions

– The execution of an action can affect the truth of a subsequently evaluated condition so the choice is significant.

Page 8: 05027240 Database systems Database Application Development

8

Triggers in SQL/3

• Events: INSERT, DELETE, or UPDATE statements or changes to individual rows caused by these statements

• Condition: Anything allowed in a WHERE clause– No subqueries in Oracle

• Action: An individual SQL statement or a program written in the language of Procedural Stored Modules (PSM) (which can contain embedded SQL statements)

Page 9: 05027240 Database systems Database Application Development

9

Triggers in SQL:1999

• Consideration: Immediate– Condition can refer to both the state of the affected row

or table before and after the event occurs

• Execution: Immediate - can be before or after the execution of triggering event .– Action of before trigger cannot modify the database

• Granularity: Both row-level and statement-level granularity

Page 10: 05027240 Database systems Database Application Development

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

Page 11: 05027240 Database systems Database Application Development

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

Page 12: 05027240 Database systems Database Application Development

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)

Page 13: 05027240 Database systems Database Application Development

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)

Page 14: 05027240 Database systems Database Application Development

14

Stored Procedure

Page 15: 05027240 Database systems Database Application Development

15

• A function stored in the DB server

• Can be invoked multiple times

• Advantage: reduce network traffic

• Can also be written using other languages (e.g., C, Java)

• Different vendors could have different implementations– Check the manual and sample programs

Stored Procedure Overview

Page 16: 05027240 Database systems Database Application Development

16

Client Application

DB2 Client

Normal Database

Network

DB Client

Client Application

DB2 ClientStored Procedure

Applications using stored procedures Network

DB Client

DB Server

DB2

DB Server

DB2

Comparison

Page 17: 05027240 Database systems Database Application Development

17

• Allows local variables, loops, procedures, examination of one tuple at a time.

CREATE PROCEDURE <name> (<arglist>) BEGIN

<procedure statements>END@

• <Procedure Statements> can have multiple SQL statements• '@' needed for ending and running.• Each argument can be:

– IN– OUT– IN OUT

Declare Stored Procedures (NetDB2)

Page 18: 05027240 Database systems Database Application Development

18

CREATE TABLE emp(id INTEGER, salary float);

CREATE PROCEDURE UPDATE_EMP (IN idNum INTEGER, IN rate FLOAT)

LANGUAGE SQL BEGIN

UPDATE EMP SET salary = salary* (1.0 + rate) WHERE id = idNum;

END @

• Name: UPDATE_EMP. • The two parameters are of data type INTEGER and FLOAT. Both are input parameters. • LANGUAGE SQL indicates that this is an SQL procedure, so a procedure body follows the

other parameters. • The procedure body consists of a single SQL UPDATE statement, which updates rows in

the emp table. • '@' is used as the terminating character for stored procedures in NetDB2.

Example

Page 19: 05027240 Database systems Database Application Development

19

CALL UPDATE_EMP (2, 0.1);

Call Stored Procedures

Id Salary 1 100 2 200 3 300

Id Salary 1 100 2 220 3 300

CALL UPDATE_EMP (3, 0.2); Id Salary 1 100 2 220 3 360

Page 20: 05027240 Database systems Database Application Development

20

• Call another procedure in a procedure (like calling functions)

• To call a target SQL procedure within a caller SQL procedure, simply include a CALL statement with the appropriate number and types of parameters.

CREATE PROCEDURE NEST_SALES(OUT budget DECIMAL(11,2)) LANGUAGE SQL BEGIN DECLARE total INTEGER DEFAULT 0; SET total = 6; CALL SALES_TARGET(total); call another

procedure SET budget = total * 10000; END @

• “budget” is an output variable

Nested Procedures

Page 21: 05027240 Database systems Database Application Development

21

CASE statement

FOR statement

GOTO statement

IF statement

ITERATE statement

RETURN statement

WHILE statement

Similar to other programming languages.

Valid Body Statements

Page 22: 05027240 Database systems Database Application Development

22

Conditional Statements

IF <condition> THEN<statement(s)>

ELSE<statement(s)>

END IF;

Loops

LOOP ……

EXIT WHEN <condition>

……

END LOOP;

Example Statements

Page 23: 05027240 Database systems Database Application Development

23

CREATE PROCEDURE UPDATE_SALARY_IF (IN employee_number INT, IN rating SMALLINT) LANGUAGE SQL BEGIN

IF (rating = 1) THEN BEGIN

DECLARE count INT; SET counter = 10;

WHILE (counter > 0) DO UPDATE employee SET salary = salary * 1.10, bonus = 1000 WHERE empno = COUNT;

SET counter = counter – 1; END WHILE;

END ELSEIF (rating = 2) THEN UPDATE employee SET salary = salary * 1.05, bonus = 500 WHERE empno = employee_number; ELSE UPDATE employee SET salary = salary * 1.03, bonus = 0 WHERE empno = employee_number; END IF;

END @

Example 1

Page 24: 05027240 Database systems Database Application Development

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

Page 25: 05027240 Database systems Database Application Development

25

CREATE PROCEDURE BUMP_SALARY_IF (IN deptnumber SMALLINT)

LANGUAGE SQL

BEGIN

DECLARE v_salary DOUBLE;

DECLARE v_years SMALLINT;

DECLARE v_id SMALLINT;

DECLARE at_end INT DEFAULT 0;

DECLARE not_found CONDITION FOR SQLSTATE '02000'; “not found” reached

-- CAST salary as DOUBLE because SQL procedures do not support DECIMAL

DECLARE C1 CURSOR FOR

SELECT id, CAST(salary AS DOUBLE), years

FROM staff;

DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1;

Page 26: 05027240 Database systems Database Application Development

26

OPEN C1; FETCH C1 INTO v_id, v_salary, v_years; WHILE at_end = 0 DO IF (v_salary < 2000 * v_years) THEN UPDATE staff SET salary = 2150 * v_years WHERE id = v_id; ELSEIF (v_salary < 5000 * v_years) THEN IF (v_salary < 3000 * v_years) THEN UPDATE staff SET salary = 3000 * v_years WHERE id = v_id; ELSE UPDATE staff SET salary = v_salary * 1.10 WHERE id = v_id; END IF; ELSE UPDATE staff SET job = 'PREZ' WHERE id = v_id; END IF; FETCH C1 INTO v_id, v_salary, v_years; END WHILE; CLOSE C1; END

Page 27: 05027240 Database systems Database Application Development

27

Other DBs- Different vendors could have implementations of stored procedures

- Start from a sample program. Do not start from scratch!

- “Cut and paste”

Page 28: 05027240 Database systems Database Application Development

28

Embedded SQL

Page 29: 05027240 Database systems Database Application Development

29

A Program to Access Databases

• A program that includes SQL constructs.

• SQL constructs can be included in a program in two different ways:– Statement Level Interface

– Call Level Interface

Page 30: 05027240 Database systems Database Application Development

30

Statement Level Interface

• SQL constructs in application take two forms:

– Standard SQL statements (static or embedded SQL): Useful when SQL portion of program is known at compile time

– 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

• Precompiler translates statements and directives into arguments of calls to library procedures.

Page 31: 05027240 Database systems Database Application Development

31

Call Level Interface

• Application program written entirely in host language (no precompiler)– Examples: JDBC, ODBC

• SQL statements are values of string variables constructed at run time using host language – As with dynamic SQL

• Application uses strings as arguments of library routines that communicate with DBMS– e.g. executeQuery(“SQL query statement”)

Page 32: 05027240 Database systems Database Application Development

32

Embedded SQL• You can embed SQL statements into many programming

languages procedural power (loops, variables, etc.)• The main components of embedded SQL programming:

– Regular program blocks

– SQL code

– Methods to connect to the database, invoke the SQL code and retrieve results

– Methods to pass data from program variables to the SQL code

– Methods to retrieve data from the result of queries to program variables

Page 33: 05027240 Database systems Database Application Development

33

Static SQL

• Declaration section for host/SQL communication

• Colon convention for value (WHERE) and result (INTO) parameters

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;

Page 34: 05027240 Database systems Database Application Development

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

Page 35: 05027240 Database systems Database Application Development

35

Cursor Overview

• Result set - set of rows produced by a SELECT statement

• Cursor - pointer to a row in the result set.

• Cursor operations:– Declaration

– Open - execute SELECT to determine result set and initialize pointer

– Fetch - advance pointer and retrieve next row

– Close - deallocate cursor

Page 36: 05027240 Database systems Database Application Development

36

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

Page 37: 05027240 Database systems Database Application Development

37

Cursor Types• Insensitive cursor: Result set (effectively) computed and

stored in a separate table at OPEN time– Changes made to base table subsequent to OPEN (by any

transaction) do not affect result set– Cursor is read-only

• Cursors that are not insensitive: Specification not part of SQL standard – Changes made to base table subsequent to OPEN (by any

transaction) can affect result set– Cursor is updatable

Page 38: 05027240 Database systems Database Application Development

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

Page 39: 05027240 Database systems Database Application Development

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

Page 40: 05027240 Database systems Database Application Development

40

Scrolling

• If SCROLL option not specified in cursor declaration, FETCH always moves cursor forward one position

• If SCROLL option is included, cursor can be moved in arbitrary ways around result set

FETCH PRIOR FROM GetEnroll INTO :studid, :grade;

• Also FIRST, LAST, ABSOLUTE n, RELATIVE n

Page 41: 05027240 Database systems Database Application Development

41

#include <stdio.h>

exec sql include sqlca;

int main()

{

exec sql begin declare section; /* declare SQL host variables */

char cust_id[5];

char cust_name[14];

float cust_discnt; /* host var for discnt value */

char user_name[20], user_pwd[20];

exec sql end declare section;

exec sql whenever sqlerror goto report_error; /* error trap condition */

exec sql whenever not found goto notfound; /* not found condition */

/*C code for reading user_name and user_pwd */

exec sql connect :user_name

identified by :user_pwd; /* ORACLE format: connect */

while (true) {

/* C code for reading customer id from stdin */

exec sql select cname,

discnt into :cust_name, :cust_discnt /* retrieve cname, discnt */

from customers where cid = :cust_id;

exec sql commit work; /* release read lock on row */

printf("CUSTOMER'S NAME IS %s AND DISCNT IS %5.1f\n",

cust_name, cust_discnt); /* NOTE, (:) not used here */

continue;

Page 42: 05027240 Database systems Database Application Development

42

ProC

• Each ESQL statement starts with EXEC SQL keyword and ends with a semicolon ;

• A pre-compiler will scan a program file and only read the statements enclosed within EXEC SQL statements and disregard everything else.

• SQLCA is a specific data structure for storing status codes of all SQL operations

/* always have this for error handling*/exec sql include sqlca ;

Page 43: 05027240 Database systems Database Application Development

43

Program.pc

Program.c

Page 44: 05027240 Database systems Database Application Development

44

Variables in ESQL

• All variables that will be used in an SQL statement must be declared using an ESQL declaration and data type

exec sql begin declare section ; VARCHAR e_name[30], username[30], passwd[30] ; INTEGER e_ssn, e_dept_id ;

exec sql end declare section ;

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

• To execute any command, you must first connect to a database in which all your tables reside.

exec sql connect :username identified by :passwd ;

Page 45: 05027240 Database systems Database Application Development

45

Executing SQL commands• Suppose we want to find the name of an employee given his/her

SSN (input by the user of the program):exec sql select name, dept_id into :e_name, :e_dept_id

from employeewhere ssn = :e_ssn ;

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

Compare the above query with the expression below. What is the difference?exec sql select name, dept_id

from employee where ssn = e_ssn ;

Program variables are preceded by “:”

Page 46: 05027240 Database systems Database Application Development

46

Dealing with Strings• There is a mismatch between the definition of a string in Oracle

and in C/C++. – In C, the end of a string is identified by the null character ‘\0’. Hence,

“Zaki” would be stored as characters ‘Z’,’a’,’k’,’i’,’\0’.

– In Oracle, the length of a string is stored together with the string and there is no special end of string character.

– If you convert a data string from Oracle to C, you must pad it with ‘\0’ manually!

• The data type VARCHAR e_name[30] is translated by the pre-compiler to the following structure:

struct {unsigned short lenunsigned char arr[30]

} e_name ;

Page 47: 05027240 Database systems Database Application Development

47

More on stringsPutting the pieces together:

strcpy(username.arr, “Zaki”) ;username.len = strlen(“Zaki”) ;strcpy(passwd.arr, “tweety-bird”) ;passwd.len = strlen(“tweety-bird”) ;

exec sql connect :username identified by :passwd ;scanf(“%d”, &e_ssn) ;

exec sql select name, dept_id into :e_name, :e_dept_idfrom employee where ssn = :e_ssn ;

e_name.arr[e_name.len] = ‘\0’ ; /* so can use string in C*/printf(“%s”, e_name.arr) ;

exec sql commit work ; /* make any changes permanent */exec sql disconnect ; /* disconnect from the database */

Page 48: 05027240 Database systems Database Application Development

48

ESQL - Cursors

• When a select statement returns a set of tuples, then the tuples (rows) can only be retrieved one by one.

– programming language variables can contain only one value at a time

– this is sometimes called an impedance mismatch

• Cursor operations

– declare a cursor using a regular SQL query (no “into”).

exec sql declare emps_dept cursor forselect ssn, name from employeewhere dept_id = :e_dept_id ;

Page 49: 05027240 Database systems Database Application Development

49

ESQL – More Cursors

• More cursor operations

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

exec sql open emps_dept ;

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

exec sql fetch emps_dept into :e_ssn, :e_name ;

Page 50: 05027240 Database systems Database Application Development

50

How do we know end of cursor?• Each SQL statement executed in a program produces a

status code that can be retrieved from the SQL Communication Area (SQLCA) variables.

• Check the “sqlcode” to see if the end of a cursor is reached (expected value depends on the system).

if (sqlca.sqlcode == -1) { … }• Error handling statements

exec sql whenever sqlerror {continue, stop, goto label, call function}

– exec sql whenever is a trap condition, it hold for all exec sql statements unless a new trap condition overrides the current one.

Page 51: 05027240 Database systems Database Application Development

51

Transactions• The most common ESQL statements are SELECT,

INSERT INTO, and UPDATE statements.• 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– exec sql commit work ;

/* changes to the database are made permanent */– exec sql rollback work ;

/* restore all tuples to their original values */• If a program did not complete correctly, then changes can

be undone to restore a consistent state.

Page 52: 05027240 Database systems Database Application Development

52

Dynamic SQL

• st is an SQL variable; names the SQL statement

• tmp, crscode, num_enrolled are host language variables (note colon notation)

• crscode is an in parameter, supplies value for placemarker (?)

• num_enrolled is an out parameter, receives value from C.NumEnrolled

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;

Page 53: 05027240 Database systems Database Application Development

53

Dynamic SQL

• PREPARE names SQL statement st and sends it to DBMS for preparation

• EXECUTE causes the statement named st to be executed

Page 54: 05027240 Database systems Database Application Development

54

Dynamic SQL• In Dynamic SQL, embedded SQL statements are created on the fly using

strings!– these strings are fed to an exec sql statement

exec sql execute immediate :sql_string• Dynamic SQL statements are not known to pre-compiler at compile time;

they must be optimized at run time!• Create a query once using a prepare statement and run it multiple times

using the execute statement.

strcpy(sqltext.arr, “delete from employee

where ssn = ?”) ;sqltext.len=str.len(sqltext.arr) ;exec sql prepare del_emp from :sqltext ;exec sql execute del_emp using :cust_id ;

Page 55: 05027240 Database systems Database Application Development

55

SQLDA• When we execute a dynamic SQL statement, we do not know which

columns will be returned and how many columns will be returned.

• The SQLDA descriptor definition allows us to find the number of columns and the value for each column.

exec sql include sqlda ;

exec sql declare sel_curs cursor for sel_emps ;exec sql prepare sel_emps from :sqltext ;exec sql describe sel_emps into sqlda ;

exec sql open sel_curs ;exec sql fetch sel_curs using descriptor sqlda ;

Page 56: 05027240 Database systems Database Application Development

56

Descriptorstemp = “SELECT C.NumEnrolled, C.Name FROM Course C WHERE C.CrsCode = ‘CS305’ ”

NumEnrolledinteger Namestring

desc

DBMS

application

GET DESCRIPTOR

1. Application fetches name, type2. Then gets value into appropriate

host variable3. Then displays name and value.

Valuenametype

Page 57: 05027240 Database systems Database Application Development

57

JDBC

• Call-level interface for executing SQL from a Java program– Methods of object classes are procedures of CLI

• SQL statement constructed at run time as the value of a Java variable (as in dynamic SQL)

• JDBC dialect of SQL can be interfaced to any DBMS (driver does the translation)

Page 58: 05027240 Database systems Database Application Development

58

JDBC Organization

DBMS

applicationdriver

manager

driver 3

driver 2

driver 1

DBMS

Page 59: 05027240 Database systems Database Application Development

59

JDBC – Dynamic SQL

• Driver is a piece of software that enables communication between a program and a database system (DMBS specific packages).

• It implements a number of main classes:– Connection (opening, closing, committing)– Statement (executing queries)– Result set (going through cursors, extracting

information)

Page 60: 05027240 Database systems Database Application Development

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

Page 61: 05027240 Database systems Database Application Development

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

Page 62: 05027240 Database systems Database Application Development

62

Result Sets and Cursors

• Three types of result sets:– Forward-only: not scrollable– Scroll-insensitive: scrollable, changes made to

underlying tables subsequent to result set computation not visible through result set

– Scroll-sensitive: scrollable, changes made to underlying tables subsequent to result set computation are visible through result set

Page 63: 05027240 Database systems Database Application Development

63

Result Set

• Any result set type can be declared read-only or updatable (assuming SQL query satisfies same conditions as an updatable view)

• 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

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.

Page 64: 05027240 Database systems Database Application Development

64

Handling Exceptions

• try/catch is the basic structure within which an SQL statement should be embedded

• If an exception is thrown, an exception object is created and the catch clause is executed

• The exception object has methods to print an error message, return SQLSTATE, etc.

try {...Java/JDBC code...}catch ( SQLException ex { handle exception } )

Page 65: 05027240 Database systems Database Application Development

65

Transactions in JDBC

• Default for a connection is – autocommit mode: each SQL statement is a transaction.

• To group statements use con.setautocommit (false)

– default isolation level of DBMS• To change isolation level use

• Transaction on connection con is committed using con.commit. Next transaction automatically initiated (chaining)

• Transactions on each connection committed separately

con.setTransactionIsolationLevel(TRANSACTION_SERIALIZABLE )

Page 66: 05027240 Database systems Database Application Development

66

import java.sql.*;import oracle.sql.*;import oracle.jdbc.driver.*;

class Employee{ public static void main (String args []) throws

SQLException {//Set your user name and the password String userName = "dummy" ; String passWord = "dummy" ;

// Load the Oracle JDBC driver DriverManager.registerDriver(new

oracle.jdbc.driver.OracleDriver());

Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@vcmr57.server.rpi.edu:1521:ora8",

userName,passWord);

Page 67: 05027240 Database systems Database Application Development

67

// Create a statement which will return a cursor that will allow you to // scroll the result set using both "next" and "previous" methods

Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

ResultSet rset = stmt.executeQuery ("SELECT name, oid FROM items ");

// Iterate through the result and print the item names while (rset.next ()) {

//Get item name, which is the first column System.out.println (rset.getString (1)); PreparedStatement pstmt = conn.prepareStatement ("SELECT name FROM owners WHERE oid = ?") ; //Feed owner id retrieved from rset into pstmt pstmt.setInt(1, rset.getInt (2));

ResultSet dset = pstmt.executeQuery() ; if (dset.next()) System.out.println(dset.getString (1)); } } }