CPS 116: Intro to Database Systems - SQL Programming, Overview, Impedance Mismatch, PSM, Slides of Introduction to Database Management Systems

An introduction to sql programming as part of the cps 116 course on introduction to database systems. Topics covered include the motivation for using sql, the impedance mismatch between sql and general-purpose programming languages, and the solution of using cursors and persistent stored modules (psm). The document also includes examples of using psm to update student records in a database.

Typology: Slides

2011/2012

Uploaded on 01/29/2012

arold
arold 🇺🇸

4.7

(24)

372 documents

1 / 4

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
SQL: Programming
CPS 116
Introduction to Database Systems
2
Announcements
Homework #1 graded
Pick up graded homework from my office
Verify your grades on Blackboard
Discussion session 4-4:40pm this Friday (Sep. 23)
in D106
Homework #2 due in 5 days
Project milestone #1 due in 7 days
3
Motivation
Pros and cons of SQL
Very high-level, possible to optimize
Not intended for general-purpose computation
Solutions
Augment SQL with constructs from general-purpose
programming languages (SQL/PSM)
Use SQL together with general-purpose programming
languages (JDBC, embedded SQL, etc.)
4
Impedance mismatch and a solution
SQL operates on a set of records at a time
Typical low-level general-purpose programming languages
operates on one record at a time
)Solution: cursor
Open (a table or a result table): position the cursor just before the
first row
Get next: move the cursor to the next row and return th at row;
raise a flag if there is no such row
Close: clean up and release DBMS resources
)Found in virtually every database language/API (with slightly
different syntaxes)
)Some support more cursor positioning and movement options,
modification at the current cursor position (analogous to the view
update problem), etc.
5
Augmenting SQL: SQL/PSM
PSM = Persistent Stored Modules
CREATE PROCEDURE proc_name ( parameter_declarations )
local_declarations
procedure_body;
CREATE FUNCTION func_name ( parameter_declarations )
RETURNS return_type
local_declarations
procedure_body;
CALL proc_name ( parameters );
Inside procedure body:
SET variable = CALL func_name ( parameters );
6
SQL/PSM example
CREATE FUNCTION SetMaxGPA(IN newMaxGPA FLOAT )
RETURNS INT
-- Enforce newMaxGPA; return number of rows modified.
BEGIN
DECLARE rowsUpdated INT DEFAULT 0;
DECLARE thisGPA FLOAT;
-- A cursor to range over all students:
DECLARE studentCursor CUSOR FOR
SELECT GPA FROM Student
FOR UPDATE;
-- Set a flag whenever there is a “not found” exception:
DECLARE noMoreRows INT DEFAULT 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET noMoreRows = 1;
… (see next slide) …
RETURN rowsUpdated;
END
pf3
pf4

Partial preview of the text

Download CPS 116: Intro to Database Systems - SQL Programming, Overview, Impedance Mismatch, PSM and more Slides Introduction to Database Management Systems in PDF only on Docsity!

SQL: Programming

CPS 116

Introduction to Database Systems

Announcements

™ Homework #1 graded

ƒ Pick up graded homework from my office

ƒ Verify your grades on Blackboard

™ Discussion session 4-4:40pm this Friday (Sep. 23)

in D

™ Homework #2 due in 5 days

™ Project milestone #1 due in 7 days

3

Motivation

™ Pros and cons of SQL

ƒ Very high-level, possible to optimize

ƒ Not intended for general-purpose computation

™ Solutions

ƒ Augment SQL with constructs from general-purpose

programming languages (SQL/PSM)

ƒ Use SQL together with general-purpose programming

languages (JDBC, embedded SQL, etc.)

4

Impedance mismatch and a solution

™ SQL operates on a set of records at a time

™ Typical low-level general-purpose programming languages

operates on one record at a time

) Solution: cursor

ƒ Open (a table or a result table): position the cursor just before the

first row

ƒ Get next: move the cursor to the next row and return that row;

raise a flag if there is no such row

ƒ Close: clean up and release DBMS resources

)Found in virtually every database language/API (with slightly

different syntaxes)

)Some support more cursor positioning and movement options,

modification at the current cursor position (analogous to the view

update problem), etc.

5

Augmenting SQL: SQL/PSM

™ PSM = Persistent Stored Modules

™ CREATE PROCEDURE proc_name ( parameter_declarations )

local_declarations

procedure_body ;

™ CREATE FUNCTION func_name ( parameter_declarations )

RETURNS return_type

local_declarations

procedure_body ;

™ CALL proc_name ( parameters );

™ Inside procedure body:

SET variable = CALL func_name ( parameters );

6

SQL/PSM example

CREATE FUNCTION SetMaxGPA(IN newMaxGPA FLOAT) RETURNS INT -- Enforce newMaxGPA; return number of rows modified. BEGIN DECLARE rowsUpdated INT DEFAULT 0; DECLARE thisGPA FLOAT; -- A cursor to range over all students: DECLARE studentCursor CUSOR FOR SELECT GPA FROM Student FOR UPDATE; -- Set a flag whenever there is a “not found” exception: DECLARE noMoreRows INT DEFAULT 0; DECLARE CONTINUE HANDLER FOR NOT FOUND SET noMoreRows = 1; … (see next slide) … RETURN rowsUpdated; END

SQL/PSM example continued

-- Fetch the first result row: OPEN studentCursor; FETCH FROM studentCursor INTO thisGPA; -- Loop over all result rows: WHILE noMoreRows <> 1 DO IF thisGPA > newMaxGPA THEN -- Enforce newMaxGPA: UPDATE Student SET Student.GPA = newMaxGPA WHERE CURRENT OF studentCursor; -- Update count: SET rowsUpdated = rowsUpdated + 1; END IF; -- Fetch the next result row: FETCH FROM studentCursor INTO thisGPA; END WHILE; CLOSE studentCursor;

Other SQL/PSM features

™ Assignment using scalar query results

ƒ SELECT INTO

™ Other loop constructs

ƒ FOR, REPEAT UNTIL, LOOP

™ Flow control

ƒ GOTO

™ Exceptions

ƒ SIGNAL, RESIGNAL

9

Interfacing SQL with another language

™ API approach

ƒ SQL commands are sent to the DBMS at runtime

ƒ Examples: JDBC, ODBC (for C/C++/VB), Perl DBI

ƒ These API’s are all based on the SQL/CLI (Call-Level

Interface) standard

™ Embedded SQL approach

ƒ SQL commands are embedded in application code

ƒ A precompiler checks these commands at compile-time

and converts them into DBMS-specific API calls

ƒ Examples: embedded SQL for C/C++, SQLJ (for Java)

10

Example API: JDBC

™ JDBC (Java DataBase Connectivity) is an API that allows a

Java program to access databases

// Use the JDBC package: import java.sql.*; … public class … { … static { // Load the JDBC driver: Class.forName(”COM.ibm.db2.jdbc.net.DB2Driver”); … } … }

11

Connections

// Connection URL is a DBMS-specific string:

String url =

”jdbc:db2://rack40.cs.duke.edu/dbcourse”;

// Making a connection:

Connection con =

DriverManager.getConnection(url);

// Closing a connection:

con.close();

12

Statements

// Create an object for sending SQL statements: Statement stmt = con.createStatement(); // Execute a query and get its results: ResultSet rs = stmt.executeQuery(”SELECT SID, name FROM Student”); // Work on the results: … // Execute a modification (returns the number of rows affected): int rowsUpdated = stmt.executeUpdate (”UPDATE Student SET name = ’Barney’ WHERE SID = 142”); // Close the statement: stmt.close(); …

JDBC drivers – Types I, II

™ Type I (bridge): translate JDBC calls to a standard

API not native to the DBMS (e.g., JDBC-ODBC

bridge)

ƒ Driver is easy to build using existing standard API’s

ƒ Extra layer of API adds overhead

™ Type II (native API, partly Java): translates JDBC

calls to DBMS-specific client API calls

ƒ DBMS-specific client library needs to be installed on

each client

ƒ Good performance

JDBC drivers – Types III, IV

™ Type III (network bridge): sends JDBC requests to a

middleware server which in turn communicates with a

database

ƒ Client JDBC driver is completely Java, easy to build, and does not

need to be DBMS-specific

ƒ Middleware adds translation overhead

™ Type IV (native protocol, full Java): converts JDBC

requests directly to native network protocol of the DBMS

ƒ Client JDBC driver is completely Java but is also DBMS-specific

ƒ Good performance

21

Embedded C example

/* Declare variables to be “shared” between the application

and the DBMS: */

EXEC SQL BEGIN DECLARE SECTION;

int thisSID; float thisGPA;

EXEC SQL END DECLARE SECTION;

/* Declare a cursor: */

EXEC SQL DECLARE CPS116Student CURSOR FOR

SELECT SID, GPA FROM Student

WHERE SID IN

(SELECT SID FROM Enroll WHERE CID = ’CPS116’)

FOR UPDATE;

22

Embedded C example continued

/* Open the cursor: / EXEC SQL OPEN CPS116Student; / Specify exit condition: / EXEC SQL WHENEVER NOT FOUND DO break; / Loop through result rows: / while (1) { / Get column values for the current row: / EXEC SQL FETCH CPS116Student INTO :thisSID, :thisGPA; printf(”SID %d: current GPA is %f\n”, thisSID, thisGPA); / Update GPA: / printf(”Enter new GPA: ”); scanf(”%f”, &thisGPA); EXEC SQL UPDATE Student SET GPA = :thisGPA WHERE CURRENT OF CPS116Student; } / Close the cursor: */ EXEC SQL CLOSE CPS116Student;

23

Pros and cons of embedded SQL

™ Pros

ƒ More compile-time checking (syntax, type, schema, …)

ƒ Code could be more efficient (if the embedded SQL

statements do not need to checked and recompiled at

run-time)

™ Cons

ƒ DBMS-specific

  • Vendors have different precompilers which translate code into

different native API’s

  • Application executable is not portable (although code is)
  • Application cannot talk to different DBMS at the same time

24

Pros and cons of augmenting SQL

™ Cons

ƒ Already too many programming languages

ƒ SQL is already too big

ƒ General-purpose programming constructs complicate

optimization make it difficult to tell if code running

inside the DBMS is safe

ƒ At some point, one must recognize that SQL and the

DBMS engine are not for everything!

™ Pros

ƒ More sophisticated stored procedures and triggers

ƒ More application logic can be pushed closer to data