1 SQL Programming Embedded SQL Call-Level Interface Java Database Connectivity Persistent Stored Modules.

Slides:



Advertisements
Similar presentations
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
Advertisements

AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
1 Database-Connection Libraries Call-Level Interface Java Database Connectivity PHP.
Winter 2002Arthur Keller – CS 1806–1 Schedule Today: Jan. 22 (T) u SQL Queries. u Read Sections Assignment 2 due. Jan. 24 (TH) u Subqueries, Grouping.
Chapter 9 SQL in a Server Environment Call-Level Interface Java Database Connectivity PHP.
CSC343 – Introduction to databases – A. Vaisman1 Database Application Development.
UJeffrey D. Ullman uAnfang von: CS145 - Herbst Stanford University uOnline unter: Folien mit weißem Hintergrund wurden.
1 Combining SQL and Conventional Programming Languages Source: slides by Jeffrey Ullman.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
Fall 2001Arthur Keller – CS 18011–1 Schedule Oct. 30 (T) Embedded SQL. u Read Section 8.1. u Assignment 5 due. Not accepted late. u Project Part 4 due.
1 Chapter 7 System Aspects of SQL uSQL in a Programming Environment uTransactions uAuthorization.
Fall 2001Arthur Keller – CS 18010–1 Schedule Oct. 25 (TH) More Constraints, Triggers. u Read Sections Oct. 30 (T) Embedded SQL. u Read Section.
Winter 2002Arthur Keller – CS 18010–1 Schedule Today: Feb. 5 (T) u Triggers, PL/SQL. u Read Sections 7.4, 8.2. Assignment 4 due. Feb. 7 (TH) u PL/SQL,
Winter 2002Arthur Keller – CS 1809–1 Schedule Today: Jan. 31 (TH) u Constraints. u Read Sections , Project Part 3 due. Feb. 5 (T) u Triggers,
1 SQL/PSM Procedures Stored in the Database General-Purpose Programming.
Winter 2002Arthur Keller – CS 18011–1 Schedule Today: Feb. 7 (TH) u PL/SQL, Embedded SQL, CLI, JDBC. u Read Sections 8.1, Feb. 12 (T) Advising.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
1 PL/SQL Oracle’s Version of Triggers and PSM. 2 PL/SQL uOracle uses a variant of SQL/PSM which it calls PL/SQL. uPL/SQL not only allows you to create.
1 CSC 440 Database Management Systems JDBC This presentation uses slides and lecture notes available from
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
CS411 Database Systems Kazuhiro Minami 07: SQL System Aspects.
CIS Computer Programming Logic
Announcements Read JDBC Project Step 5, due Monday.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 9- 1 DATADABASE PROGRAMMING 2Chapter 13 from our text.
1 Real SQL Programming Embedded SQL Call-Level Interface Java Database Connectivity.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Triggers, PL/SQL, embedded SQL, JDBC.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Chapter 8 Using SQL in an Application. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-2 CSC 4480 outline Intro (3-9) Static SQL (10-11)
Winter 2006Keller, Ullman, Cushing10–1 Modification to Views Via Triggers Oracle allows us to “intercept” a modification to a view through an instead-of.
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
1 Real SQL Programming Embedded SQL Java Database Connectivity Stored Procedures.
Winter 2006 Keller, Ullman, Cushing 11–1 Embedded SQL Add to a conventional programming language (C in our examples) certain statements that represent.
SQL in a Programming Environment CIS 4301 Lecture Notes Lecture /11/2006.
1 Real SQL Programming - 2 Persistent Stored Modules (PSM) PL/SQL Embedded SQL These slides are reused from Jeffrey Ullman’s class with the author’s permission.
Databases 1 9th lecture. Main topic: Oracle PL/SQL What is PL/SQL? ▫Procedural Langauge extension for standard SQL.. PL/SQL not only allows you to create.
Introduction to PL/SQL. Main topic: Oracle PL/SQL What is PL/SQL? ▫Procedural Langauge extension for standard SQL.. PL/SQL not only allows you to create.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
Chapter 4 An Introduction to SQL. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.4-2 Topics in this Chapter SQL: History and Overview The.
Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery.
SQL Programming SQL in Application Programs
SCU Fall 2002JoAnne Holliday10–1 Schedule Today u Triggers, Procedures, PL/SQL. u Read Sections , 8.1, 8.5. Next u Transaction concepts, security.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
Chapter 7: Constraints and Triggers Foreign Keys Local and Global Constraints Triggers 1.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Embedded SQL, JDBC. u Read Sections.
1 Database Design: DBS CB, 2 nd Edition SQL in a Server Environment: CLI & JDBC & Security Ch Ch. 9.6 – Ch 10.1.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL (modified 11/11/2013)
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
1 Database Design: DBS CB, 2 nd Edition SQL in a Server Environment: Stored Procedure & Embedded SQL Ch. 9.3, 9.4.
1 Introduction to Database Systems, CS420 SQL Persistent Stored Modules (PSM) – Stored Procedure.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
SQL in the real world 1. The Three-Tier Architecture of Database Applications browser network HTTP Web server Application server Database server database.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Application Development Chapter 6.
SQL in the real world 1. The SQL Client-Server Interactions SQL-clientSQL-server Environment SQL-agent Module Connection Session Current catalog and schema.
SCU Fall 2002JoAnne Holliday10–1 Schedule Today u Embedded SQL. u Read Sections 8.1, 8.5. Next u Transaction concepts, security u Read Sections 8.6 – 8.7.
1 Lecture 11 PL/SQL Slides from
SQL Environment.
Introduction to Database Systems, CS420
CMSC-461 Database Management Systems
Foreign Keys Local and Global Constraints Triggers
CPSC-608 Database Systems
CPSC-310 Database Systems
CPSC-310 Database Systems
CPSC-310 Database Systems
T. Jumana Abu Shmais – AOU - Riyadh
Persistent Stored Modules (PSM) PL/SQL Embedded SQL
Database-Connection Libraries
Modification to Views Via Triggers
Embedded SQL Chapter 8.
Presentation transcript:

1 SQL Programming Embedded SQL Call-Level Interface Java Database Connectivity Persistent Stored Modules

2 SQL in Real Programs We have seen only how SQL is used at the generic query interface --- an environment where we sit at a terminal and ask queries of a database. Reality is almost always different. –Programs in a conventional language like C are written to access a database by “calls” to SQL statements.

3 Host Languages Any conventional language can be a host language, that is, a language in which SQL calls are embedded. The use of a host/SQL combination allows us to do anything computable, yet still get the very- high-level SQL interface to the database.

4 Connecting SQL to the Host Language 1.Embedded SQL is a standard for combining SQL with seven languages. 2.CLI (Call-Level Interface ) is a different approach to connecting C to an SQL database. 3.JDBC (Java Database Connectivity ) is a way to connect Java with an SQL database.

5 Embedded SQL Key idea: Use a preprocessor to turn SQL statements into procedure calls that fit with the host-language code surrounding. All embedded SQL statements begin with EXEC SQL, so the preprocessor can find them easily.

6 Shared Variables To connect SQL and the host-language program, the two parts must share some variables. Declarations of shared variables are bracketed by: EXEC SQL BEGIN DECLARE SECTION; EXEC SQL END DECLARE SECTION; Always needed

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

8 Example: Looking Up Prices We’ll use C with embedded SQL to 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.

9 Example: C Plus SQL EXEC SQL BEGIN DECLARE SECTION; char theBar[21], theBeer[21]; float thePrice; EXEC SQL END DECLARE SECTION; /* obtain values for theBar and theBeer */ EXEC SQL SELECT price INTO :thePrice FROM Sells WHERE bar = theBar AND beer = theBeer; /* do something with thePrice */ Note 21-char arrays needed for 20 chars + endmarker SELECT-INTO just like PSM

10 Embedded Queries Embedded SQL has the same limitations as PSM regarding queries: –You may use SELECT-INTO for a query guaranteed to produce a single tuple. –Otherwise, you have to use a cursor. Small syntactic differences between PSM and Embedded SQL cursors, but the key ideas are identical.

11 Cursor Statements Declare a cursor c with: EXEC SQL DECLARE c CURSOR FOR ; 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 ; –Macro NOT FOUND is true if and only if the FETCH fails to find a tuple.

12 Example -- 1 Let’s write C + SQL to print Joe’s menu --- the list of beer-price pairs that we find in Sells(bar, beer, price) with bar = Joe’s Bar. A cursor will visit each Sells tuple that has bar = Joe’s Bar.

13 Example – 2 (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 = ‘Joe’’s Bar’; The cursor declaration goes outside the declare-section

14 Example – 3 (Executable) EXEC SQL OPEN CURSOR c; while(1) { EXEC SQL FETCH c INTO :theBeer, :thePrice; if (NOT FOUND) break; /* format and print theBeer and thePrice */ } EXEC SQL CLOSE CURSOR c; The C style of breaking loops

15 Need for Dynamic SQL Most applications use specific queries and modification statements in their interaction with the database. –Thus, we can compile the EXEC SQL … statements into specific procedure calls and produce an ordinary host- language program that uses a library. What if the program is something like a generic query interface, that doesn’t know what it needs to do until it runs?

16 Dynamic SQL Preparing a query: EXEC SQL PREPARE FROM ; Executing a query: EXEC SQL EXECUTE ; “Prepare” = optimize query. Prepare once, execute many times.

17 Example: A Generic Interface EXEC SQL BEGIN DECLARE SECTION; char query[MAX_LENGTH]; EXEC SQL END DECLARE SECTION; while(1) { /* issue SQL> prompt */ /* read user’s 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

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

19 Example: Generic Interface Again EXEC SQL BEGIN DECLARE SECTION; char query[MAX_LENGTH]; EXEC SQL END DECLARE SECTION; while(1) { /* issue SQL> prompt */ /* read user’s query into array query */ EXEC SQL EXECUTE IMMEDIATE :query; }

20 SQL Call-Level-Interface

21 SQL/CLI Instead of using a preprocessor, we can use a library of functions and call them as part of an ordinary C program. –The library for C is called SQL/CLI = “Call-Level Interface.” –Embedded SQL’s preprocessor will translate the EXEC SQL … statements into CLI or similar calls, anyway.

22 Data Structures C connects to the database by structs of the following types: 1.Environments : represent the DBMS installation. 2.Connections : logins to the database. 3.Statements : records that hold SQL statements to be passed to a connection. 4.Descriptions : records about tuples from a query or parameters of a statement.

23 Environments, Connections, and Statements Function SQLAllocHandle(T,I,O) is used to create these structs, which are called environment, connection, and statement handles. –T = type, e.g., SQL_HANDLE_STMT. –I = input handle = struct at next higher level (statement < connection < environment). –O = (address of) output handle.

24 Example: SQLAllocHandle SQLAllocHandle(SQL_HANDLE_STMT, myCon, &myStat); myCon is a previously created connection handle. myStat is the name of the statement handle that will be created.

25 Preparing and Executing SQLPrepare(H, S, L) causes the string S, of length L, to be interpreted as an SQL statement, optimized, and the executable statement is placed in statement handle H. SQLExecute(H) causes the SQL statement represented by statement handle H to be executed.

26 Example: Prepare and Execute SQLPrepare(myStat, “SELECT beer, price FROM Sells WHERE bar = ‘Joe’’s Bar’”, SQL_NTS); SQLExecute(myStat); This constant says the second argument is a “null-terminated string”; i.e., figure out the length by counting characters.

27 Dynamic Execution If we will execute a statement S only once, we can combine PREPARE and EXECUTE with: SQLExecuteDirect(H,S,L); –As before, H is a statement handle and L is the length of string S.

28 Fetching Tuples When the SQL statement executed is a query, we need to fetch the tuples of the result. –That is, a cursor is implied by the fact we executed a query, and need not be declared. SQLFetch(H) gets the next tuple from the result of the statement with handle H.

29 Accessing Query Results When we fetch a tuple, we need to put the components somewhere. Thus, each component is bound to a variable by the function SQLBindCol. –This function has 6 arguments, of which we shall show only 1, 2, and 4: 1.1 = handle of the query statement. 2.2 = column number. 3.4 = address of the variable.

30 Example: Binding Suppose we have just done SQLExecute(myStat), where myStat is the handle for query SELECT beer, price FROM Sells WHERE bar = ‘Joe’’s Bar’ Bind the result to theBeer and thePrice: SQLBindCol(myStat, 1,, &theBeer,, ); SQLBindCol(myStat, 2,, &thePrice,, );

31 Example: Fetching Now, we can fetch all the tuples of the answer by: while ( SQLFetch(myStat) != SQL_NO_DATA) { /* do something with theBeer and thePrice */ } CLI macro representing SQLSTATE = = “failed to find a tuple.”

32 JDBC

33 JDBC Java Database Connectivity (JDBC) is a library similar to SQL/CLI, but with Java as the host language. JDBC/CLI differences are often related to the object-oriented style of Java, but there are other differences.

34 Environments, Connections, and Statements The same progression from environments to connections to statements that we saw in CLI appears in JDBC. A connection object is obtained from the environment in a somewhat implementation- dependent way. We’ll start by assuming we have myCon, a connection object.

35 Statements JDBC provides two classes: 1.Statement = an object that can accept a string that is an SQL statement and can execute such a string. 2.PreparedStatement = an object that has an associated SQL statement ready to execute.

36 Creating Statements The Connection class has methods to create Statements and PreparedStatements. Statement stat1 = myCon.createStatement(); PreparedStatement stat2 = myCon.createStatement( “SELECT beer, price FROM Sells” + “WHERE bar = ‘Joe’’s Bar’” ); Java trick: + concatenates strings. createStatement with no argument returns a Statement; with one argument it returns a PreparedStatement.

37 Executing SQL Statements JDBC distinguishes queries from modifications, which it calls “updates.” Statement and PreparedStatement each have methods executeQuery and executeUpdate. –For Statements, these methods have one argument: the query or modification to be executed. –For PreparedStatements: no argument.

38 Example: Update stat1 is a Statement. We can use it to insert a tuple as: stat1.executeUpdate( “INSERT INTO Sells” + “VALUES(‘Brass Rail’, ‘Bud’, 3.00)” );

39 Example: Query stat2 is a PreparedStatement holding the query “SELECT beer, price FROM Sells WHERE bar = ‘Joe’’s Bar’”. executeQuery returns an object of class ResultSet --- we’ll examine it later. The query: ResultSet Menu = stat2.executeQuery();

40 Accessing the ResultSet An object of type ResultSet is something like a cursor. Method Next() advances the “cursor” to the next tuple. –The first time Next() is applied, it gets the first tuple. –If there are no more tuples, Next() returns the value FALSE.

41 Accessing Components of Tuples When a ResultSet is referring to a tuple, we can get the components of that tuple by applying certain methods to the ResultSet. Method getX (i ), where X is some type, and i is the component number, returns the value of that component. –The value must have type X.

42 Example: Accessing Components Menu is the ResultSet for the query “SELECT beer, price FROM Sells WHERE bar = ‘Joe’’s Bar’”. Access the beer and price from each tuple by: while ( Menu.Next() ) { theBeer = Menu.getString(1); thePrice = Menu.getFloat(2); /* do something with theBeer and thePrice */ }

43 SQL/PSM Procedures Stored in the Database

44 Stored Procedures An extension to SQL, called SQL/PSM, or “persistent, stored modules,” allows us to store procedures as database schema elements. The programming style is a mixture of conventional statements (if, while, etc.) and SQL. Let’s us do things we cannot do in SQL alone.

45 Basic PSM Form CREATE PROCEDURE ( ) ; Function alternative: CREATE FUNCTION ( ) RETURNS

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

47 Example: Stored Procedure Let’s write a procedure that takes two arguments b and p, and adds a tuple to Sells that has bar = ’Joe’’s Bar’, beer = b, and price = p. –Used by Joe to add to his menu more easily.

48 The Procedure CREATE PROCEDURE JoeMenu ( INbCHAR(20), IN pREAL ) INSERT INTO Sells VALUES(’Joe’’s Bar’, b, p); Parameters are both read-only, not changed The body --- a single insertion

49 Invoking Procedures Use SQL/PSM statement CALL, with the name of the desired procedure and arguments. Example: CALL JoeMenu(’Moosedrool’, 5.00); Functions used in SQL expressions where a value of their return type is appropriate.

50 Types of PSM statements -- 1 RETURN sets the return value of a function. –Unlike C, etc., RETURN does not terminate function execution. DECLARE used to declare local variables. BEGIN... END for groups of statements. –Separate by semicolons.

51 Types of PSM Statements -- 2 Assignment statements: SET = ; –Example: SET b = ’Bud’; Statement labels: give a statement a label by prefixing a name and a colon.

52 IF statements Simplest form: IF THEN END IF; Add ELSE if desired, as IF... THEN... ELSE... END IF; Add additional cases by ELSEIF : IF … THEN … ELSEIF … ELSEIF … ELSE … END IF;

53 Example: IF Let’s rate bars by how many customers they have, based on Frequents(drinker, bar). –<100 customers: ‘unpopular’. – customers: ‘average’. –>= 200 customers: ‘popular’. Function Rate(b) rates bar b.

54 Example: IF (continued) CREATE FUNCTION Rate (IN b CHAR(20) ) RETURNS CHAR(10) DECLARE cust INTEGER; 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; Number of customers of bar b Return occurs here, not at one of the RETURN statements Nested IF statement

55 Loops Basic form: LOOP END LOOP; Exit from a loop by: LEAVE The is associated with a loop by prepending the name and a colon to the keyword LOOP.

56 Example: Exiting a Loop loop1: LOOP... LEAVE loop1;... END LOOP; If this statement is executed... Control winds up here

57 Other Loop Forms WHILE DO END WHILE; REPEAT UNTIL END REPEAT;

58 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.Cursors.

59 Example: Assignment/Query If p is a local variable and Sells(bar, beer, price) the usual relation, we can get the price Joe charges for Bud by: SET p = (SELECT price FROM Sells WHERE bar = ’Joe’’s Bar’ AND beer = ’Bud’);

60 SELECT... INTO An equivalent way to get the value of a query that is guaranteed to return a single tuple is by placing INTO after the SELECT clause. Example: SELECT price INTO p FROM Sells WHERE bar = ’Joe’’s Bar’ AND beer = ’Bud’;

61 Cursors A cursor is essentially a tuple-variable that ranges over all tuples in the result of some query. Declare a cursor c by: DECLARE c CURSOR FOR ;

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

63 Fetching Tuples From a Cursor To get the next tuple from cursor c, issue command: FETCH FROM c INTO x1, x2,…,xn ; The x ’s are a list of variables, one for each component of the tuples referred to by c. c is moved automatically to the next tuple.

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

65 Breaking Cursor Loops -- 2 Each SQL operation returns a status, which is a 5-digit number. –For example, = “Everything OK,” and = “Failed to find a tuple.” In PSM, we can get the value of the status in a variable called SQLSTATE.

66 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 by: DECLARE NotFound CONDITION FOR SQLSTATE ’02000’;

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

68 Example: Cursor Let’s write a procedure that examines Sells(bar, beer, price), and raises by $1 the price of all beers at Joe’s Bar that are under $3. –Yes, we could write this as a simple UPDATE, but the details are instructive anyway.

69 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 = ’Joe’’s Bar’); Used to hold beer-price pairs when fetching through cursor c Returns Joe’s menu

70 The Procedure Body BEGIN OPEN c; 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 = ’Joe’’s Bar’ AND beer = theBeer; END IF; END LOOP; CLOSE c; END; Check if the recent FETCH failed to get a tuple If Joe charges less than $3 for the beer, raise it’s price at Joe’s Bar by $1.