








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2
SQL statements can refer to host variables (including special variables used to return status). Must include a statement to connect to the right database.
Embed SQL in the host language (Embedded SQL, SQLJ) Create special API to call SQL commands (JDBC)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 4
SQL supports a mechanism called a cursor to handle this.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 5
A preprocessor converts the SQL statements into special API calls. Then a regular compiler is used to compile the code.
Connecting to a database: EXEC SQL CONNECT Declaring variables: EXEC SQL BEGIN (END) DECLARE SECTION Statements: EXEC SQL Statement;
char c_sname[20]; long c_sid; short c_rating; float c_age; EXEC SQL END DECLARE SECTION
Two special “error” variables: SQLCODE (long, is negative if an error has occurred) SQLSTATE (char[6], predefined codes for common errors)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 10
SQL query strings are now always known at compile time (e.g., spreadsheet, graphical DBMS frontend): Allow construction of SQL statements on-the-fly
Example: char c_sqlstring[]= {“DELETE FROM Sailors WHERE raiting>5”}; EXEC SQL PREPARE readytogo FROM :c_sqlstring; EXEC SQL EXECUTE readytogo;
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 11
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 Sun’s JDBC: Java API Supposedly DBMS-neutral a “driver” traps the calls and translates them into DBMS- specific code database can be across a network
Application (initiates and terminates connections, submits SQL statements) Driver manager (load JDBC driver) Driver (connects to data source, transmits requests and returns/translates results and error codes) Data source (processes SQL statements)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 13
Four types of drivers: Bridge: Translates SQL commands into non-native API. Example: JDBC-ODBC bridge. Code for ODBC and JDBC driver needs to be available on each client. Direct translation to native API, non-Java driver: Translates SQL commands to native API of data source. Need OS-specific binary on each client. Network bridge: Send commands over the network to a middleware server that talks to the data source. Needs only small JDBC driver at each client. Direction 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.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 14
In the Java code: Class.forName(“oracle/jdbc.driver.Oracledriver”); When starting the Java application: -Djdbc.drivers=oracle/jdbc.driver
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 19
String sql=“INSERT INTO Sailors VALUES(?,?,?,?)”; PreparedStatment pstmt=con.prepareStatement(sql); pstmt.clearParameters(); pstmt.setInt(1,sid); pstmt.setString(2,sname); pstmt.setInt(3, rating); pstmt.setFloat(4,age);
// we know that no rows are returned, thus we use executeUpdate() int numRows = pstmt.executeUpdate();
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 20
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 }
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 22
TIMESTAMP java.sql.TimeStamp getTimestamp()
TIME java.sql.Time getTime()
DATE java.sql.Date getDate()
REAL Double getFloat()
INTEGER Integer getInt()
FLOAT Double getDouble()
DOUBLE Double getDouble()
VARCHAR String getString()
CHAR String getString()
BIT Boolean getBoolean()
SQL Type Java class ResultSet get method
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 23
try { stmt=con.createStatement(); warning=con.getWarnings(); while(warning != null) { // handle SQLWarnings; warning = warning.getNextWarning(): } con.clearWarnings(); stmt.executeUpdate(queryString); warning = con.getWarnings(); … } //end try catch( SQLException SQLe) { // handle the exception }
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 28
Complements JDBC with a (semi-)static query model: Compiler 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) {sname=rs.getString(2);} else { sname2=rs.getString(2);} SQLJ (part of the SQL standard) versus embedded SQL (vendor-specific)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 29
Int sid; String name; Int rating; // named iterator #sql iterator Sailors(Int sid, String name, Int rating); Sailors sailors; // assume that the application sets rating #sailors = { SELECT sid, sname INTO :sid, :name FROM Sailors WHERE rating = :rating }; // retrieve results while (sailors.next()) { System.out.println(sailors.sid + “ “ + sailors.sname)); } sailors.close();
Two types of iterators (“cursors”): Named iterator Need both variable type and name, and then allows retrieval of columns by name. See example on previous slide. 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} ; if (sailors.endFetch()) { break; } // process the sailor }
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 31
Program executed through a single SQL statement Executed in the process space of the server
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
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 32
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
Stored procedures can have parameters: Three different modes: IN, OUT, INOUT
CREATE PROCEDURE IncreaseRating( IN sailor_sid INTEGER, IN increase INTEGER) UPDATE Sailors SET rating = rating + increase WHERE sid = sailor_sid
CREATE PROCEDURE TopSailors( IN num INTEGER) LANGUAGE JAVA EXTERNAL NAME “file:///c:/storedProcs/rank.jar”
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 37
CREATE FUNCTION rate Sailor (IN sailorId INTEGER) RETURNS INTEGER DECLARE 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;
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 38
Local variables (DECLARE) RETURN values for FUNCTION Assign variables with SET Branches and loops: IF (condition) THEN statements; ELSEIF (condition) statements; … ELSE statements; END IF; LOOP statements; END LOOP Queries can be parts of expressions Can use cursors naturally without “EXEC SQL”