8 DBApp

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 90

Database application development (Real SQL programming)

February 27, 2014

Administrivia
! Announcements
-! PS 4 is ready

! Reading assignment
-!

Chapter 6

! Today
-!

Database application development (real SQL programming)

! Acknowledgement
-! Some slide content courtesy of Ramakrishnan, Gehrke, and Ullman

SQL in real programs


! We have seen mainly how SQL is used at the generic query interface
-! in interactive mode, or -! via a script file -! (except with JDBC)

! Reality is almost always different:


-! Conventional programs interacting with SQL

SQL in application code


! SQL commands can be called from within a host language (e.g., C, C++, Java) program -! SQL statements can refer to host language variables (including special variables used to return status) -! Must include a statement to connect to the right database

Three options for integration


1.! Embed SQL in a host language
-! Embedded SQL, Dynamic SQL -! Ex: SQLJ

2.! Create special API to call SQL commands


-! SQL/CLI -! Ex: SQL/CLI for C, JDBC

3.! Database stored procedures (code in a specialized language is stored in the database itself)
-! SQL/PSM

Impedance mismatch
! Differences between programming language model and database model ! Binding for each host programming language
-! Mapping between each SQL attribute type and its compatible programming language type

! SQL relations are (multi-)sets of records, with no a priori bound on the number of records
-! No such data structure exists in host programming languages such as C++, Java -! SQL supports a mechanism called a cursor to handle this

Embedded SQL

Embedded SQL (static)


! Key idea:
-! Embed SQL in the host language -! SQL statements identified by a special prefix -! A preprocessor (or precompiler) converts the SQL statements into special API calls that fit with the surrounding host-language code -! Then a regular compiler is used to compile the code

! All embedded SQL statements begin with EXEC SQL, so the preprocessor can find them

Language constructs
! Connecting to a database
EXEC SQL CONNECT

! Declaring shared variables: To connect SQL and the hostlanguage program, the two parts must share some variables
EXEC SQL BEGIN DECLARE SECTION // variables here EXEC SQL END DECLARE SECTION

! Statements
EXEC SQL <Statement>

Use of shared variables


! In SQL, the shared variables must be preceded by a colon (:)
-! They may be used as constants provided by the host-language program -! They may get values from SQL statements and pass those values to the host-language program

! In the host language, shared variables behave like any other variable

10

Example: shared variables


EXEC SQL BEGIN DECLARE SECTION char c_sname[20]; long c_sid; short c_rating; float c_age; EXEC SQL END DECLARE SECTION

11

Communication variables
! Two special error variables:
-! SQLCODE (long, is negative if an error has occurred) -! SQLSTATE (char[6], predefined codes for common errors)

! One of these two variables must be declared

12

Embedded SQL statement


EXEC SQL INSERT INTO Sailors VALUES (:c_sname, :c_sid, :c_rating, :c_age);

It is using shared variables

13

Example: Looking up prices


! Using C with embedded SQL lets us sketch the important parts of a function that obtains a beer and a bar, and looks up the price of that beer at that bar. ! Assumes database has our usual Sells(bar, beer, price) relation

14

Example: C plus SQL


EXEC SQL BEGIN DECLARE SECTION; char theBar[21], theBeer[21]; float thePrice; EXEC SQL END DECLARE SECTION;
20 chars + endmarker

/* obtain values for theBar and theBeer */ EXEC SQL SELECT price INTO :thePrice FROM Sells WHERE bar = :theBar AND beer = :theBeer; /* do something with thePrice */

SELECT-INTO

15

Embedded queries
! Embedded SQL has the same limitations as PSM (that we will see later) regarding queries:
-! SELECT-INTO for a query guaranteed to produce a single tuple -! For multiple tuples, we have to use a cursor

16

Cursor statements
! Declare a cursor c with: EXEC SQL DECLARE c CURSOR FOR <query>; ! Open and close cursor c with: EXEC SQL OPEN CURSOR c; EXEC SQL CLOSE CURSOR c; ! Fetch from c by: EXEC SQL FETCH c INTO <variable(s)>;

17

Example: Print Joes menu


! Lets write C + SQL code to print Joes menu the list of beer-price pairs that we find in Sells(bar, beer, price) with bar = Joes Bar ! A cursor will visit each Sells tuple that has bar = Joes Bar

18

Example: Declarations
EXEC SQL BEGIN DECLARE SECTION; char theBeer[21]; float thePrice; EXEC SQL END DECLARE SECTION; EXEC SQL DECLARE c CURSOR FOR SELECT beer, price FROM Sells WHERE bar = Joes Bar;
The cursor declaration goes outside the declare-section
19

Example: Executable part


EXEC SQL OPEN CURSOR c; The C style while(1) { of breaking loops EXEC SQL FETCH c INTO :theBeer, :thePrice; if (NO_MORE_TUPLES) break; /* format and print theBeer and thePrice */ } EXEC SQL CLOSE CURSOR c; // Using the following macro: #define NO_MORE_TUPLES !(strcmp(SQLSTATE, 02000)) // 02000 means no tuple was found

20

Cursors
! A way to deal with impedance mismatch ! A cursor is essentially a tuple-variable that ranges over all tuples in the result of some query ! Can declare a cursor on a relation or query statement (which generates a relation) DECLARE c CURSOR FOR <query>;

21

Cursors (cont.)
! Can open a cursor, and repeatedly fetch a tuple then move the cursor, until all tuples have been retrieved
-! Can use a special clause, called ORDER BY, in queries that are accessed through a cursor, to control the order in which tuples are returned
! Fields in ORDER BY clause must also appear in SELECT clause

-! The ORDER BY clause, which orders answer tuples, is only allowed in the context of a cursor

! Can also modify/delete the tuple pointed to by a cursor

22

Opening and closing cursors


! To use cursor c, we must issue the command: OPEN c;
-! The query of c is evaluated, and c is set to point to the first tuple of the result

! When finished with c, issue command: CLOSE c;

23

Fetching tuples from a cursor


! To get the next tuple from cursor c, issue command: FETCH FROM c INTO x1, x2, , xn ; ! The xs are a list of variables, one for each component of the tuples referred to by c ! c is moved automatically to the next tuple

24

Breaking cursor loops (1)


! The usual way to use a cursor is to create a loop with a FETCH statement, and do something with each tuple fetched ! A tricky point is how we get out of the loop when the cursor has no more tuples to deliver

25

Breaking cursor loops (2)


! Each SQL operation returns a status, which is a 5-digit character string
-! For example, 00000 = Everything OK, and 02000 = Failed to find a tuple

! We can get the value of the status in a variable called SQLSTATE

26

Breaking cursor loops (3)


! We may declare a condition, which is a boolean variable that is true if and only if SQLSTATE has a particular value ! Example: We can declare condition NotFound to represent 02000 by: DECLARE NotFound CONDITION FOR SQLSTATE 02000;

27

Breaking cursor loops (4)


! The structure of a cursor loop is thus: cursorLoop: LOOP ... FETCH c INTO ... ; IF NotFound THEN LEAVE cursorLoop; END IF; ... END LOOP;

28

Cursor that gets names of sailors whove reserved a red boat, in alphabetical order
EXEC SQL DECLARE sinfo CURSOR FOR SELECT S.sname FORM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=red ORDER BY S.sname

! Note that it is illegal to replace S.sname by, say, S.sid in the ORDER BY clause because S.sid does not appear in SELECT!

29

Example: Embedding SQL in C


char SQLSTATE[6]; EXEC SQL BEGIN DECLARE SECTION char c_sname[20]; short c_minrating; float c_age; EXEC SQL END DECLARE SECTION c_minrating = random(); EXEC SQL DECLARE sinfo CURSOR FOR SELECT S.sname, S.age FROM Sailors S WHERE S.rating > :c_minrating ORDER BY S.sname; EXEC SQL OPEN sinfo; do { EXEC SQL FETCH sinfo INTO :c_sname; :c_age; printf(%s is %d years old\n, c_sname, c_age); } while (SQLSTATE != 02000); // 02000 means NO DATA EXEC SQL CLOSE sinfo;
30

Need for Dynamic SQL


! Most applications use specific queries and modification statements to interact with the database
-! The DBMS compiles EXEC SQL statements into specific procedure calls and produces an ordinary host-language program that uses a library

! What about the query the host language program reads in from the user, which doesnt know what it needs to do until it runs?
-! SQL query strings are not always known at compile time -! E.g., spreadsheet or a graphical DBMS frontend allows construction of SQL statements on-the-fly

31

Dynamic SQL example


char c_sqlstring[] = {DELETE FROM Sailors WHERE rating>5} EXEC SQL PREPARE readytogo FROM :c_sqlstring; EXEC SQL EXECUTE readytogo;

32

Dynamic SQL constructs


! Preparing a query: EXEC SQL PREPARE <query-name> FROM <text of the query>; ! Executing a query: EXEC SQL EXECUTE <query-name>; ! Prepare = optimize query ! Prepare once, execute many times

33

Example: A generic interface


EXEC SQL BEGIN DECLARE SECTION; char query[MAX_LENGTH]; EXEC SQL END DECLARE SECTION; while(1) { /* issue SQL> prompt */ /* read users query into array query */ EXEC SQL PREPARE q FROM :query; EXEC SQL EXECUTE q; } q is an SQL variable
representing the optimized form of whatever statement is typed into :query

34

Execute-immediate
! If we are only going to execute the query once, we can combine the PREPARE and EXECUTE steps into one ! Use: EXEC SQL EXECUTE IMMEDIATE <text>;

35

Example: Generic interface again


EXEC SQL BEGIN DECLARE SECTION; char query[MAX_LENGTH]; EXEC SQL END DECLARE SECTION; while(1) { /* issue SQL> prompt */ /* read users query into array query */ EXEC SQL EXECUTE IMMEDIATE :query; }

36

Call-Level Interface (CLI)


Alternative to embedding

37

Call-Level Interface (CLI)


Rather than modify compiler, add library with database calls (API) ! Special standardized interface: procedures/objects ! Pass SQL strings from language, presents result sets in a language-friendly way ! SQL/CLI ! Suns JDBC: Java API ! Supposedly DBMS-neutral
-! A driver traps the calls and translates them into DBMS-specific code -! Database can be across a network

38

JDBC architecture
Four architectural components: ! Application
-! initiates and terminates connections -! submits SQL statements

Will skip JDBC since weve already studied it. I will leave these slides in for your reference though.

! Driver manager
-! Loads JDBC driver

! Driver
-! Connects to data source -! Transmits requests and -! Returns/translates results and error codes

! Data source
-! Processes SQL statements
39

JDBC architecture (cont.)


Four types of drivers
! Bridge
-! Translates SQL commands into non-native API -! Ex: JDBC-ODBC bridge (code for ODBC and JDBC driver needs to be available on each client)

! Direct translation to native API via non-Java driver


-! Translates SQL commands to native API of data source -! Needs OS-specific binary on each client

! Network bridge
-! Sends commands over the network to a middleware server that talks to the data source. -! Needs only small JDBC driver at each client

! Direct translation to native API via Java driver


-! Converts JDBC calls directly to network protocol used by DBMS -! Needs DBMS-specific Java driver at each client
40

JDBC classes and interfaces


Steps to submit a database query ! Load the JDBC driver ! Connect to the data source ! Execute SQL statements

41

JDBC driver management


! All drivers are managed by the DriverManager class ! Loading a JDBC driver
-! In the Java code Class.forName(oracle.jdbc.driver.OracleDriver); Class.forName(com.mysql.jdbc.Driver); -! When starting the Java application -Djdbc.drivers=oracle.jdbc.driver

42

Connections in JDBC
! We interact with a data source through sessions
-! Each connection identifies a logical session

! JDBC URL:
-! Jdbc:<subprotocol>.<otherParameters>

! Example:
String url=jdbc:oracle:www.bookstore.com:3083; Connection con; try { con = DriverManager.getConnection(url,userid,passwd); } catch SQLException excpt { . . . } // MySQL example: DriverManager.getConnection( "jdbc:mysql://localhost:3306/bookstore", //database name "alee", // username allowme"); // password
43

Connection class interface


public int getTransactionIsolation() public void setTransactionIsolation(int level)
-! Sets isolation level for the current connection

public boolean getReadOnly() public void setReadOnly(boolean b)


-! Specifies whether transactions in this connection are read-only

public boolean getAutoCommit() public void setAutoCommit(boolean b)


-! If autocommit is set, then each SQL statement is considered its own transaction -! Otherwise, a transaction is committed using commit(), or aborted using rollback()

public boolean isClosed()


-! Checks whether connection is still open
44

Executing SQL statements


! Three different ways of executing SQL statements
-! Statement
! Both static and dynamic SQL statements

-! PreparedStatement
! Semi-static SQL statements

-! CallableStatement
! Stored procedures

! PreparedStatement class
-! Precompiled, parameterized SQL statements
! Structure is fixed ! Values of parameters are determined at run-time

45

Executing SQL statements (cont.)


String sql=INSERT INTO Sailors VALUES(?,?,?,?); PreparedStatement pstmt=con.prepareStatement(sql); pstmt.clearParameters(); pstmt.setInt(1, sid); pstmt.setString(2, sname); pstmt.setInt(3, rating); pstmt.setFloat(4, age); // No rows are returned so use executeUpdate (insert, update, alter, // delete) // Use executeQuery if it returns rows (select) int numRows = pstmt.executeUpdate();

46

ResultSets
! PreparedStatement.executeUpdate only returns the number of affected records ! PreparedStatement.executeQuery returns data, encapsulated in a ResultSet object (a cursor)
ResultSet rs=pstmt.executeQuery(sql); // rs is now a cursor while (rs.next()) { // process the data }

47

ResultSets (cont.)
A ResultSet is a very powerful cursor ! previous()
-! moves one row back

! absolute(int num)
-! moves to the row with the specified number

! relative(int num)
-! moves forward or backward

! first() ! last()

48

Example: ResultSet
String query = SELECT ; ResultSet rs = stmt.executeQuery(query); while (rs.next()) { isbn = rs.getString(1); title = rs.getString(TITLE); // process isbn and title }

49

Matching Java and SQL data types


SQL Type BIT CHAR VARCHAR DOUBLE FLOAT INTEGER REAL DATE TIME TIMESTAMP Java class Boolean String String Double Double Integer Double Java.sql.Date Java.sql.Time Java.sql.TimeStamp ResultSet get method getBoolean() getString() getString() getDouble() getDouble() getInt() getFloat() getDate() getTime() getTimestamp()

50

JDBC: exceptions and warning


! Most of java.sql can throw an SQLException if an error occurs (cf. SQLSTATE) ! SQLWarning is a subclass of SQLException
-! Not as severe -! They are not thrown and their existence has to be explicitly tested

51

Warning and exceptions (cont.)


try { stmt=con.createStatement(); warning=con.getWarnings(); while (warning != null) { // handle SQLWarnings warning = warning.getNextWarning(); } con.clearWarnings(); stmt.executeUpdate(queryString); warning = con.getWarnings(); } catch (SQLException sqle) { // handle the exception }
52

Examining database metadata


! DatabaseMetaData object gives information about the database system and the catalog DatabaseMetaData md = con.getMetaData(); // print information about the driver System.out.println(Name: + md.getDriverName() + version: + md.getDriverVersion());

53

Database metadata (cont.)


DatabaseMetaData md = con.getMetaData(); ResultSet trs=md.getTables(null,null,null,null); String tableName; while (trs.next()) { tableName = trs.getString(TABLE_NAME); System.out.println(Table: + tableName); // prints all attributes ResultSet crs = md.getColumns(null,null,tableName,null); while (crs.next()) { System.out.println(crs.getString(COLUMN_NAME) + ); } // prints out the primary keys of this table System.out.println(The keys of table + tableName + are:); ResultSet krs = md.getPrimaryKeys(null,null,tableName); while (krs.next()) { System.out.println(krs.getString(COLUMN_NAME) + ); } }

54

A (semi-)complete example
Connection con = // connect DriverManager.getConnection(url, login, passwd); Statement stmt = con.createStatement(); // set up stmt String query = SELECT name, rating FROM Sailors; ResultSet rs = stmt.executeQuery(query); try { while (rs.next()) { // loop through result tuples String s = rs.getString(name); int n = rs.getInt(rating); System.out.println(s + + n); } } catch (SQLException ex) { System.out.println(ex.getMessage() + + ex.getSQLState() + + ex.getErrorCode()); }
55

CLI Examples for C and Java


! See a complete example each for both Java and C ! See DB.java and Bank1.java from an earlier lecture on JDBC for Java ! See cmysql.c for C

56

SQLJ
! SQLJ should really be in the Embedded SQL section of this slide set, but I located it here so that you can compare it with JDBC ! Embedded SQL with Java ! Preprocessor for SQLJ into Java ! Complements JDBC with a semi-static query model ! SQLJ (part of the SQL standard) versus embedded SQL (vendor-specific) ! [I am providing these slides for SQLJ, but we wont go over them in class. Its an optional topic.]
57

SQLJ vs. JDBC


! With SQLJ, compilers can perform syntax checks, strong type checks, consistency of the query with the schema
-! All arguments always bound to the same variable
#sql = { SELECT name, rating INTO :name, :rating FROM Books WHERE sid = :sid; }

-! Compare to JDBC
Sid = rs.getInt(1); if (sid==1) sname1 = rs.getString(2); else sname2 = rs.getString(2);

58

SQLJ code
Int sid; Sting name; Int rating; // 1. Declare the iterator class (cursor!) #sql iterator Sailors(Int sid, String name, Int rating); // 2. Instantiate an iterator object Sailors sailors; // 3. Initialize the iterator #sql sailors = { SELECT sid, sname INTO :sid, :name FROM Sailors WHERE rating = :rating }; // 4. Retrieve results while (sailors.next()) { System.out.println(sailors.sid + + sailors.sname)); } // 5. Close the iterator object sailors.close();
59

Corresponding JDBC code


PreparedStatement stmt = connection.prepareStatement( SELECT sid, sname FROM Sailors WHERE rating=?); // set the parameter in the query and execute it stmt.setInt(1, rating); ResultSet rs = stmt.executeQuery(); // retrieve the results while (rs.next()) { System.out.println(rs.getInt(1) + + rs.getString(2)); }

60

SQLJ iterators
Two types of iterators (cursors) ! Named iterator
-! Need both variable type and name, and then allows retrieval of columns by name -! See example two slides ago

! Positional iterator
-! Need only variable type, and then uses FETCH INTO construct #sql iterator Sailors(Int, String, Int); Sailors sailors; #sailors = . . . while (true) { #sql {FETCH :sailors INTO :sid, :name, :rating}; if (sailors.endFetch()) { break; } // process the sailor }
61

Alternative to Embedding and CLI

Stored Procedures

62

Stored Procedures
! PSM (Persistent Stored Modules) allows us to store procedures as database schema elements (SQL:2003) ! A stored procedure is
-! A program executed through a single SQL statement -! Executed in the process space of the server -! PSM = a mixture of conventional statements (if, while, etc.) and SQL

! Advantages
-! -! -! -! Lets us do things we cannot do in SQL alone Can encapsulate application logic while staying close to the data Reuse of application logic by different users Avoid tuple-at-a-time return of records through cursors

! Most DBMSs allow users to write stored procedures in a simple, general-purpose language (close to SQL)
-! A SQL/PSM standard is a representative
63

Basic PSM Form


CREATE PROCEDURE <name> ( <parameter list> ) <optional local declarations> <procedure body>; ! Function alternative: CREATE FUNCTION <name> ( <parameter list> ) RETURNS <sqlDataType> <optional local declarations> <function body>;
64

Parameters in PSM
! Unlike the usual name-type pairs in languages like C, PSM uses mode-name-type triples, where the mode can be:
-! IN = procedure uses value, does not change value -! OUT = procedure changes, does not use -! INOUT = both

65

Example: Stored procedure (next)


! Lets write a procedure that takes two arguments b and p, and adds a tuple to Sells(bar, beer, price) that has bar = Joes Bar, beer = b, and price = p
-! Used by Joe to add to his menu more easily

66

The procedure (definition)


CREATE PROCEDURE JoeMenu ( IN b CHAR(20), IN p REAL ) INSERT INTO Sells VALUES(Joes Bar, b, p);

Parameters are both read-only, not changed

The body a single insertion

67

Invoking procedures
! Use SQL/PSM statement CALL, with the name of the desired procedure and actual arguments ! Example: CALL JoeMenu(Moosedrool, 5.00); ! Functions used in SQL expressions wherever a value of their return type is appropriate

68

Kinds of PSM statements (1)


! RETURN <expression> sets the return value of a function
-! Unlike C, etc., RETURN does not terminate function execution

! DECLARE <name> <type> used to declare local variables ! BEGIN . . . END for groups of statements
-! Separate statements by semicolons

! Not surprising it requires most of the language constructs in this language too. After all, you need those to create functions as in any language powerful enough to support functions!!!
69

Kinds of PSM statements (2)


! Assignment statements: SET <variable> = <expression>;
-! Example: SET b = Bud;

! Statement labels: give a statement a label by prefixing a name and a colon

70

IF statements
! Simplest form: IF <condition> THEN <statements(s)> END IF; ! Add ELSE <statement(s)> if desired, as IF . . . THEN . . . ELSE . . . END IF; ! Add additional cases by ELSEIF <statements(s)>: IF THEN ELSEIF THEN ELSEIF THEN ELSE END IF;

71

Example: IF
! Lets rate bars by how many customers they have, based on Frequents(drinker,bar)
-! <100 customers: unpopular -! 100-199 customers: average -! >= 200 customers: popular

! Function Rate(b) rates bar b

72

Example: IF (cont.)
CREATE FUNCTION Rate (IN b CHAR(20) ) Number of RETURNS CHAR(10) customers of DECLARE cust INTEGER; bar b BEGIN SET cust = (SELECT COUNT(*) FROM Frequents WHERE bar = b); IF cust < 100 THEN RETURN unpopular ELSEIF cust < 200 THEN RETURN average ELSE RETURN popular END IF; END;
Return occurs here, not at one of the RETURN statements
73

Loops
! Basic form: <loop name>: LOOP <statements> END LOOP; ! Exit from a loop by: LEAVE <loop name>

74

Example: Exiting a loop


loop1: LOOP . . . LEAVE loop1; . . . END LOOP;

If this statement is executed . . .

Control winds up here

75

Other loop forms


! WHILE <condition> DO <statements> END WHILE; ! REPEAT <statements> UNTIL <condition> END REPEAT;

76

1. Queries
! General SELECT-FROM-WHERE queries are not permitted in PSM There are three ways to get the effect of a query:
1.! Queries producing one value can be the expression in an assignment 2.! Single-row SELECT . . . INTO 3.! Can use cursors naturally without EXEC SQL

77

Example: Assignment/Query
! Using local variable p and Sells(bar, beer, price), we can get the price Joe charges for Bud by: SET p = (SELECT price FROM Sells WHERE bar = Joes Bar AND beer = Bud);

78

2. SELECT . . . INTO
! Another way to get the value of a query that returns one tuple is by placing INTO <variable> after the SELECT clause. ! Example: SELECT price INTO p FROM Sells WHERE bar = Joes Bar AND beer = Bud;

79

3. Cursor
! Lets write a procedure that examines Sells(bar, beer, price), and raises by $1 the price of all beers at Joes Bar that are under $3
-! Yes, we could write this as a simple UPDATE, but the details are instructive anyway

80

The needed declarations


CREATE PROCEDURE JoeGouge( ) DECLARE theBeer CHAR(20); DECLARE thePrice REAL; DECLARE NotFound CONDITION FOR SQLSTATE 02000; DECLARE c CURSOR FOR (SELECT beer, price FROM Sells WHERE bar = Joes Bar);
Used to hold beer-price pairs when fetching through cursor c

Returns Joes menu


81

The procedure body


Check if the recent BEGIN FETCH failed to OPEN c; get a tuple menuLoop: LOOP FETCH c INTO theBeer, thePrice; IF NotFound THEN LEAVE menuLoop END IF; IF thePrice < 3.00 THEN UPDATE Sells SET price = thePrice + 1.00 WHERE bar = Joes Bar AND beer = theBeer; END IF; END LOOP; CLOSE c; If Joe charges less than $3 for END; the beer, raise its price at Joes Bar by $1

82

More examples
CREATE PROCEDURE ShowNumReservations SELECT S.sid, S.sname, COUNT(*) FROM Sailors S, Reserves R WHERE S.sid = R.sid GROUP BY S.sid, S.sname CREATE PROCEDURE IncreaseRating( IN sailorId INTEGER, IN increase INTEGER) UPDATE Sailors SET rating = rating + increase WHERE sid = sailorId

83

Stored procedures in any language


! Stored procedures do not have to be written in SQL CREATE PROCEDURE TopSailors (IN num INTEGER) LANGUAGE JAVA EXTERNAL NAME file://c:/storedProcs/rank.jar

84

Example: Calling stored procedures


EXEC SQL BEGIN DECLARE SECTION Int sid; Int rating; EXEC SQL END DECLARE SECTION // now increase the rating of this sailor EXEC CALL IncreaseRating(:sid, :rating);

85

Ex: Calling stored procedures (cont.)


JDBC: CallableStatement cstmt=con.prepareCall({call ShowSailors}); ResultSet rs=cstmt.executeQuery(); while (rs.next()) { . . . } SQLJ: #sql Iterator ShowSailors(. . .); ShowSailors showsailors; #sql showsailors={CALL ShowSailors}; while (showsailors.next()) { . . . }
86

Example: function
CREATE FUNCTION rateSailor(IN sailorId INTEGER) RETURNS INTEGER DECALRE rating INTEGER DECLARE numRes INTEGER SET numRes = (SELECT COUNT(*) FROM Reserves R WHERE R.sid = sailorId) IF (numRes > 10) THEN rating = 1; ELSE rating = 0; END IF; RETURN rating;
87

Summary of SQL/PSM constructs


! ! ! ! Local variables (DECLARE) RETURN values for FUNCTION Assign variables with SET Branches and loops
-! IF (<condition>) THEN <statements>; ELSEIF (<condition>) THEN <statements>; . . . ELSE <statements>; END IF; -! LOOP <statements>; END LOOP;

! Queries can be parts of expressions ! Can use cursors naturally without EXEC SQL
88

Summary
! Embedded SQL allows execution of parameterized static queries within a host language ! Dynamic SQL allows execution of completely ad hoc queries within a host language ! Cursor mechanism allows retrieval of one record at a time and bridges impedance mismatch between host language and SQL ! APIs such as JDBC introduce a layer of abstraction between application and DBMS

89

Summary (cont.)
! SQLJ: static model, queries checked at compile-time ! Stored procedures execute application logic directly at the server ! SQL/PSM standard for writing stored procedures

90

You might also like