Database Application Development Overview SQL in Application Code SQL in Application Code (Contd.) Embedded SQL Embedded SQL: Va
Total Page:16
File Type:pdf, Size:1020Kb
Overview Concepts covered in this lecture: Database Application Development SQL in application code Embedded SQL Cursors Chapter 6 Dynamic SQL JDBC SQLJ Stored procedures Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2 SQL in Application Code SQL in Application Code (Contd.) SQL commands can be called from within a host language (e.g., C++ or Java) program. Impedance mismatch: SQL statements can refer to host variables SQL relations are (multi-) sets of records, with (including special variables used to return status). no a priori bound on the number of records. Must include a statement to connect to the right No such data structure exist traditionally in database. procedural programming languages such as Two main integration approaches: C++. (Though now: STL) Embed SQL in the host language (Embedded SQL, SQL supports a mechanism called a cursor to SQLJ) handle this. Create special API to call SQL commands (JDBC) Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 3 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 4 Embedded SQL Embedded SQL: Variables Approach: Embed SQL in the host language. A preprocessor converts the SQL statements into special API calls. EXEC SQL BEGIN DECLARE SECTION Then a regular compiler is used to compile the char c_sname[20]; code. long c_sid; short c_rating; float c_age; Language constructs: EXEC SQL END DECLARE SECTION Connecting to a database: EXEC SQL CONNECT Declaring variables: Two special “error” variables: EXEC SQL BEGIN (END) DECLARE SECTION SQLCODE (long, is negative if an error has occurred) Statements: SQLSTATE (char[6], predefined codes for common errors) EXEC SQL Statement; Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 5 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 6 Cursors Cursor that gets names of sailors who’ve reserved a red boat, in alphabetical order Can declare a cursor on a relation or query statement (which generates a relation). EXEC SQL DECLARE sinfo CURSOR FOR SELECT S.sname Can open a cursor, and repeatedly fetch a tuple then FROM Sailors S, Boats B, Reserves R move the cursor, until all tuples have been retrieved. WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ ORDER BY S.sname Can use a special clause, called ORDER BY, in queries that are accessed through a cursor, to control the order in Note that it is illegal to replace S.sname by, say, which tuples are returned. ORDER BY • Fields in ORDER BY clause must also appear in SELECT clause. S.sid in the clause! (Why?) The ORDER BY clause, which orders answer tuples, is only Can we add S.sid to the SELECT clause and allowed in the context of a cursor. replace S.sname by S.sid in the ORDER BY clause? Can also modify/delete tuple pointed to by a cursor. Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 7 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 8 Embedding SQL in C: An Example Dynamic SQL char SQLSTATE[6]; EXEC SQL BEGIN DECLARE SECTION char c_sname[20]; short c_minrating; float c_age; SQL query strings are now always known at compile EXEC SQL END DECLARE SECTION time (e.g., spreadsheet, graphical DBMS frontend): c_minrating = random(); Allow construction of SQL statements on-the-fly EXEC SQL DECLARE sinfo CURSOR FOR SELECT S.sname, S.age FROM Sailors S WHERE S.rating > :c_minrating Example: ORDER BY S.sname; char c_sqlstring[]= do { {“DELETE FROM Sailors WHERE raiting>5”}; EXEC SQL FETCH sinfo INTO :c_sname, :c_age; printf(“%s is %d years old\n”, c_sname, c_age); EXEC SQL PREPARE readytogo FROM :c_sqlstring; } while (SQLSTATE != ‘02000’); EXEC SQL EXECUTE readytogo; EXEC SQL CLOSE sinfo; Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 9 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 10 Database APIs: Alternative to JDBC: Architecture embedding Rather than modify compiler, add library with database calls (API) Four architectural components: Application (initiates and terminates connections, Special standardized interface: procedures/objects submits SQL statements) Pass SQL strings from language, presents result sets in a language-friendly way Driver manager (load JDBC driver) Driver (connects to data source, transmits requests Sun’s JDBC: Java API and returns/translates results and error codes) Supposedly DBMS-neutral Data source (processes SQL statements) a “driver” traps the calls and translates them into DBMS- specific code database can be across a network Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 11 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 12 JDBC Architecture (Contd.) JDBC Classes and Interfaces Four types of drivers: Bridge: Steps to submit a database query: Translates SQL commands into non-native API. Example: JDBC-ODBC bridge. Code for ODBC and JDBC 1. Load the JDBC driver driver needs to be available on each client. Direct translation to native API, non-Java driver: 2. Connect to the data source Translates SQL commands to native API of data source. 3. Execute SQL statements 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 13 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 14 JDBC Driver Management Connections in JDBC All drivers are managed by the We interact with a data source through sessions. Each DriverManager class connection identifies a logical session. JDBC URL: Loading a JDBC driver: jdbc:<subprotocol>:<otherParameters> In the Java code: Class.forName(“oracle/jdbc.driver.Oracledriver”); Example: When starting the Java application: String url=“jdbc:oracle:www.bookstore.com:3083”; -Djdbc.drivers=oracle/jdbc.driver Connection con; try{ con = DriverManager.getConnection(url,usedId,password); } catch SQLException excpt { …} Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 15 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 16 Connection Class Interface Executing SQL Statements public int getTransactionIsolation() and void setTransactionIsolation(int level) Three different ways of executing SQL Sets isolation level for the current connection. statements: public boolean getReadOnly() and Statement (both static and dynamic SQL void setReadOnly(boolean b) statements) Specifies whether transactions in this connection are read- PreparedStatement (semi-static SQL statements) only CallableStatment (stored procedures) public boolean getAutoCommit() and void setAutoCommit(boolean b) If autocommit is set, then each SQL statement is PreparedStatement class: considered its own transaction. Otherwise, a transaction is Precompiled, parametrized SQL statements: committed using commit(), or aborted using rollback(). Structure is fixed public boolean isClosed() Values of parameters are determined at run-time Checks whether connection is still open. Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 17 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 18 Executing SQL Statements (Contd.) ResultSets String sql=“INSERT INTO Sailors VALUES(?,?,?,?)”; PreparedStatment pstmt=con.prepareStatement(sql); PreparedStatement.executeUpdate only returns the pstmt.clearParameters(); number of affected records pstmt.setInt(1,sid); PreparedStatement.executeQuery returns data, pstmt.setString(2,sname); encapsulated in a ResultSet object (a cursor) pstmt.setInt(3, rating); pstmt.setFloat(4,age); ResultSet rs=pstmt.executeQuery(sql); // rs is now a cursor // we know that no rows are returned, thus we use While (rs.next()) { executeUpdate() // process the data int numRows = pstmt.executeUpdate(); } Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 19 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 20 ResultSets (Contd.) Matching Java and SQL Data Types SQL Type Java class ResultSet get method A ResultSet is a very powerful cursor: BIT Boolean getBoolean() CHAR String getString() previous(): moves one row back VARCHAR String getString() absolute(int num): moves to the row with the specified number DOUBLE Double getDouble() FLOAT Double getDouble() relative (int num): moves forward or INTEGER Integer getInt() backward REAL Double getFloat() first() and last() DATE java.sql.Date getDate() TIME java.sql.Time getTime() TIMESTAMP java.sql.TimeStamp getTimestamp() Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 21 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 22 JDBC: Exceptions and Warnings Warning and Exceptions (Contd.) try { stmt=con.createStatement(); Most of java.sql can throw and SQLException warning=con.getWarnings(); if an error occurs. while(warning != null) { // handle SQLWarnings; SQLWarning is a subclass of EQLException; warning = warning.getNextWarning(): not as severe (they are not thrown and their } existence has to be explicitly tested) 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 23 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 24 Examining Database