


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
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
1 / 4
This page cannot be seen from the preview
Don't miss anything!



3
4
5
6
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
-- 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;
9
10
// Use the JDBC package: import java.sql.*; … public class … { … static { // Load the JDBC driver: Class.forName(”COM.ibm.db2.jdbc.net.DB2Driver”); … } … }
11
12
// 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(); …
21
22
/* 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
24