SQL DML and DB Applications, JDBC Week 4.2 Week 4 MIE253-Consens 1
Schedule Week Date Lecture Topic 1 Jan 9 Introduction to Data Management 2 Jan 16 The Relational Model 3 Jan. 23 Constraints and SQL DDL 4 Jan. 30 SQL DML, DB Applications, JDBC 5 Feb 6 Relational Algebra 6 Feb 13 Advanced SQL - Feb 20 [Reading Week] 7 Feb 27 Review and Midterm (Mar 1) 8 Mar 5 OLAP 9 Mar 12 ER Conceptual Modelling 10 Mar 19 Normalization 11 Mar 26 XML and Data Integration 12 Apr 2 Transactions and the Internet, Query Processing 13 Apr 9 Final Review This week s reading: Chapter 5 (5.3) Chapter 8 (8.5, 8.2.5) Previous week s: Chapters 1-2 Chapter 3 Week 4 MIE253-Consens 2
JDBC Reading Material Chapter 8 Textbook (focus: Section 8.5) On-line JDBC tutorial http://docs.oracle.com/javase/tutorial/jdbc/i ndex.html See also, Lab handouts and code samples On-line JDBC reference http://docs.oracle.com/javase/1.3/docs/guide /jdbc/index.html Thinking in Java background reading (assigned in the Lab) Week 4 MIE253-Consens 3
JDBC Why? Gain a basic understanding of how to program Database-driven applications Gain exposure to enterprise class frameworks What is JDBC? - Call-level interface (CLI) for executing SQL from a Java program Call-level in Java = Method invocation SQL statements are constructed at run time as the value of a Java variable JDBC passes SQL statements to the underlying DBMS and receives the results Can interface any DBMS that has a JDBC driver Week 4 MIE253-Consens 4
JDBC Run-Time Architecture Access database JDBC-ODBC driver ODBC Data Source Java application driver manager SQLServer driver SQLServer database DB/2 driver DB/2 DBMS database Week 4 MIE253-Consens 5
Getting a connection import java.sql.*; -- import all classes in package java.sql Class.forName (driver name); // static method of class Class // loads specified driver Connection con = DriverManager.getConnection(Url, Id, Passwd); Static method of class DriverManager; attempts to connect to DBMS If successful, creates a connection object, con, for managing the connection Statement stat = con.createstatement (); Creates a statement object stat Statements have executequery() method Week 4 MIE253-Consens 6
JDBC Class Usage DriverManager Driver Connection Statement executequery ResultSet Week 4 MIE253-Consens 7
Executing a Query String query = SELECT T.StudId FROM Transcript T + WHERE T.CrsCode = MIE253 + AND T.Semester = S2012 ; ResultSet res = stat.executequery (query); Creates a result set object, res. Prepares and executes the query. Stores the result set produced by execution in res (analogous to opening a cursor). The query string can be constructed at run time (as above). The input parameters are plugged into the query when the string is formed (as above) Week 4 MIE253-Consens 8
Preparing a Query String query = SELECT T.StudId FROM Transcript T + WHERE T.CrsCode =? AND T.Semester =? ; placeholders PreparedStatement ps = con.preparestatement ( query ); Prepares the statement Creates a prepared statement object, ps, containing the prepared statement Placeholders (?) mark positions of in parameters; special API is provided to plug the actual values in positions indicated by the? s Week 4 MIE253-Consens 9
Executing a Prepared Query String crs_code, semester; ps.setstring(1, crs_code); // set value of first in parameter ps.setstring(2, semester); // set value of second in parameter ResultSet res = ps.executequery ( ); No Argument! Creates a result set object, res Executes the query Stores the result set produced by execution in res while ( res.next ( ) ) { // advance the cursor j = res.getint ( StudId ); // fetch output int-value process output value } Week 4 MIE253-Consens 10
JDBC Class Diagram Week 4 MIE253-Consens 11
Handling Exceptions try {...Java/JDBC code... } catch ( SQLException ex ) { exception handling code... } try/catch is the basic structure within which an SQL statement should be embedded If an exception is thrown, an exception object, ex, is created and the catch clause is executed Week 4 MIE253-Consens 12
Handling SQL Exceptions try { s.execute(); } catch (SQLException e) { out.println("sqlexception: " + e.getmessage()); out.println("sqlstate: " + e.getsqlstate()); out.println("vendorerror: " + e.geterrorcode()); } SQLException objects have methods to print an error message, return SQLSTATE from the DBMS, etc. Week 4 MIE253-Consens 13
Re-throwing Exceptions try { s.execute(); } catch (SQLException se ) { String SQLState = se.getsqlstate(); if ( SQLState.equals( "23505" ) ) { correctduplicatekey(); } else if ( SQLState.equals( "22003" ) ) { correctarithmeticoverflow(); } else { throw se; } } SQLExceptions can have some cases handled locally and then re-thrown for additional handling Week 4 MIE253-Consens 14
Transactions in JDBC Default for a connection is autocommit mode, where each SQL statement is a transaction Each statement committed (if completed ok) To group several statements into a transaction con.setautocommit (false) All the statements in transaction are committed con.commit() All the statements in transaction are aborted con.rollback() To change the isolation level of transactions con.settransactionisolationlevel (TRANSACTION_SERIALIZABLE) Week 4 MIE253-Consens 15