Professional Documents
Culture Documents
8 DBApp
8 DBApp
8 DBApp
Administrivia
! Announcements
-! PS 4 is ready
! Reading assignment
-!
Chapter 6
! Today
-!
! Acknowledgement
-! Some slide content courtesy of Ramakrishnan, Gehrke, and Ullman
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
! 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>
! In the host language, shared variables behave like any other variable
10
11
Communication variables
! Two special error variables:
-! SQLCODE (long, is negative if an error has occurred) -! SQLSTATE (char[6], predefined codes for common errors)
12
13
14
/* 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
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
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
22
23
24
25
26
27
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
! 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
32
33
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
36
37
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
! 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
41
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
-! 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
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
50
51
53
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
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
-! 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
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
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
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
66
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
! 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
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
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
75
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
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
84
85
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
! 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