JDBC Programming: Intro Most interaction with DB is not via interactive interface Most people interact via 1. Application programs directly 2. Apps over the internet There are 3 general approaches to developing application programs: Special purpose languages Provided by a specific DBMS Included as part of the DBMS environment E.g., Oracle PL/SQL, MySQL s stored procedures, etc. Embedded programming DB commands embedded in standard programming language DB commands flagged by special prefix (e.g., EXEC SQL) Program preprocessed before compilation: Flagged statements id d by preprocessor Compiled by DB compiler Compiled code replaces code in source program being sent to language compiler Resulting program compiled by regular language compiler DB API DB accessed via API API is library of functions for accessing DBMS API presents standard interface to any DBMS Each DBMS must supply drivers for API Promotes portability across DBMSs Program communicates with DBMS via parameters passed to API functions 1
JDBC Programming: Intro (2) JDBC is an API Java is host language Basic program structure: 1. Import JDBC classes 2. Load JDBC drivers 3. Connect to DB 4. Access DB 5. Close session Details: 1. Import classes: import java.sql.* 2. Load drivers: 3. Connect: Class.forName("<driver_name>"); Connection <var> = DriverManager.getConnection(<url>); or Connection <var> = DriverManager.getConnection(<url>, <userid>, <passwd>); DriverM anager class provides basic services for managing JDBC drivers When getconnection called, DriverM anager tries to find appropriate driver Connection object returned on success Represents a DBMS session Used to access DB 2
4. Access: JDBC Programming: JDBC Intro (2) SQL statements sent to DB via Connection object 3 classes for doing this: (a) Statement For SQL statements without parameters Created using public abstract Statement createstatement() (b) PreparedStatement For SQL statements with parameters Usually used with precompiled statements - Statements used multiple times Created using public abstract PreparedStatement preparestatement(string sql) sql is SQL statement that may have IN parameters Parameters represented by question marks (c) CallableStatement For stored procedures Created using public abstract CallableStatement preparecall(string sql) sql may have IN and OUT parameters Includes methods for setting up and executing parameters 5. Close: Use public abstract void close() 3
JDBC Programming: JDBC Intro (3) Additional methods of Connection class: 1. setautocommit public abstract void setautocommit(boolean autocommit) Default Commits when either Statement completes Next execute occurs Last row of ResultSet returned ResultSet closed 2. commit public abstract void commit() Manual control of commits Only used when setautocommit disabled 3. rollback public abstract void rollback() Manual control of rollbacks Only used when setautocommit disabled 4. getmetadata public abstract DataBaseMetaData getmetadata() DataBaseMetaData object holds info about the DB proper 4
JDBC Programming: JDBC Non-query SQL Concerns DDL and non-select DML statements 3 ways to implement: 1. Statement 2. PreparedStatement 3. CallableObject 1. Statement objects: Cannot accept parameters To execute: public abstract int executeupdate(string sql) Returns number of rows processed (0 for DDL) sql is SQL statement Statement not terminated with semicolon 2. P reparedstatement objects: May have IN parameters Steps in use: (a) Instantiate prepared statement (b) Set parameter values (c) Execute prepared statement Statement is a string with parameter positions indicated using question marks To set parameter values: public abstract void setxxx(int parameterindex, XXX value) XXX represents any Java built-in data type parameterindex references position of given parameter (1-based) To execute: public abstract int executeupdate() Are precompiled Preferred method for statements that are called multiple times 5
Statements JDBC Programming: JDBC Statement Object Examples Statement stmt = conn.createstatement(); String query = "INSERT INTO MemberOf VALUES ( 20000, PHYS )"; try { int nrows = stmt.executeupdate(query); catch (SQLException e) { System.out.println("Error inserting into table"); while (e!= null) { System.out.println("Message:" + e.getmessage()); e = e.getnextexception(); return; stmt.close(); Prepared statements String query = "INSERT INTO MemberOf VALUES (?,?)"; PreparedStatement stmt = conn.preparestatement(query); String id = "12345"; String dept = "MATH"; try { stmt.setstring(1, id); stmt.setstring(2, dept); stmt.executeupdate(); catch (SQLException e) { System.out.println("Error inserting into table"); while (e!= null) { System.out.println("Message:" + e.getmessage()); e = e.getnextexception(); return; stmt.close(); 6
JDBC Programming: JDBC SELECT To execute: For Statement objects: public abstract ResultSet executequery(string sql) For P reparedstatement and CallableStatement objects: public abstract ResultSet executequery() ResultSet object receives results of a query To access results from ResultSet objects: 1. next public abstract boolean next() Every result set has an associated pointer Pointer points to row of returned table Initially positioned in front of, but not at, row 1 Every call of next moves pointer to next row 2. getxxx (a) public abstract XXX getxxx(int columnindex) Comparable to setxxx for retrieving column values from result set (b) public abstract XXX getxxx(string columnname) Comparable to above version, but uses column names instead of positional indices Generally slower than above Case insensitive SQL NULL represented as Java null 3. f indcolumn public abstract int findcolumn(string columnname) Return positional index of column with columnn ame 7
4. wasnull JDBC Programming: JDBC SELECT (2) public abstract boolean wasnull() Indicates whether last column read contains NULL 5. close public abstract void close() Will be closed automatically when either (a) Generating statement is closed (b) Generating statement is re-executed (c) When used to retrieve next result from a sequence of statements 8
JDBC Programming: JDBC SELECT Examples Statement stmt = conn.createstatement(); String coursedept = "CIS"; String query = "SELECT Dept, CNumber, Lname, Phone " + "FROM Faculty F, Teach T " + "WHERE F.Id = T.Id " + "AND Dept = " + coursedept + " "; ResultSet rs; String dept, cnumber, lname, phone; try { rs = stmt.executquery(query); catch (SQLException e) { System.out.println("Error executing SELECT"); while (e!= null) { System.out.println("Message:" + e.getmessage()); e = e.getnextexception(); return; System.out.println("Dept Nbr Name Phone"); System.out.println("=============================="); while (rs.next()) { dept = rs.getstring(1); cnumber = rs.getstring(2); lname = rs.getstring("lname"); phone = rs.getstring(4); //Print values of dept, cnumber, lname, and phone in field of // appropriate width stmt.close(); 9
getm etadata JDBC Programming: JDBC ResultSetMetaData public abstract ResultSetMetaData getmetadata() Returns metadata about table retrieved in a result set Methods for retrieving info from ResultSetM etadata objects: 1. getcolumncount public abstract int getcolumncount() Return number of columns in result set 2. isn ullable public abstract int isnullable(int column) Indicates whether column can have NULL Possible results: columnnonulls columnnullable columnnullableunknown 3. getcolumndisplaysize public abstract int getcolumndisplaysize(int column) Returns column max width 4. getcolumnlabel public abstract int getcolumnlabel(int column) Returns title used for display and printout of column 5. getcolumnn ame public abstract int getcolumnname(int column) 10
JDBC Programming: JDBC ResultSetMetaData 6. getcolumnt ype public abstract int getcolumntype(int column) Returns SQL type of column Represented by constant integers named by SQL types E.g., DOUBLE, INTEGER, VARCHAR,... 7. getcolumnt ypen ame public abstract String getcolumntypename(int column) Returns column s source-specific data type 8. getp recision public abstract int getprecision(int column) 9. getscale public abstract int getscale(int column) 10. gett ablename public abstract String gettablename(int column) Returns name of table for given column (empty string if not applicable) 11
JDBC Programming: JDBC ResultSet MetaData Examples Statement stmt = conn.createstatement(); String query = readquery(); //Read string from user ResultSet rs; String cname, val; int i, csize, ncols; try { rs = stmt.executequery(query); catch (SQLException e) { System.out.println("Error executing query"); while (e!= null) { System.out.println("Message:" + e.getmessage()); e = e.getnextexception(); return; ResultSetMetaData rsmd = rs.getmetadata(); ncols = rsmd.getcolumncount(); for (i = 1; i <= ncols; i++) { cname = rsmd.getcolumnname(i); csize = rsmd.getcolumndisplaysize(i); //Print name in field of csize width while (rs.next()) { for (int i = 1; i <= ncols; i++) { val = rs.getstring(i); csize = rsmd.getcolumndisplaysize(i); //Print value in field of csize width stmt.close(); 12
JDBC Programming: JDBC Error Handling JDBC provides 3 classes for handling problems: SQLException SQLWarning DataTruncation Error handling: 1. SQLException class Derived from java.lang.exception Exception objects contain: (a) Error message Retrieved using String getmessage() (b) SQL state Retrieved using String getsqlstate() (c) Error code (DBMS-specific) Retrieved using int geterrorcode() (d) Link to next exception Retrieved using SQLException getnextexception() General usage: try { //JDBC access statement catch (SQLException e) { //print general message while (e!= NULL) { System.out.println("Error msg = " + e.getmessage()); System.out.println("SQL state = " + e.getsqlstate()); System.out.println("Error code = " + e.geterrorcode()); e = e.getnextexception(); 2. SQLWarning class Subclass of SQLException Holds same info as SQLException objects 13
3. DataTruncation class JDBC Programming: JDBC Error Handling (2) Subclass of SQLWarning Contains info re truncations that occur during reads and writes of DB Read truncations usually generate warnings Write truncations generate exceptions DataTruncation objects contain following: Message Data truncation SQLState 01004 Indication of whether column or parameter is affected Access using public boolean getparameter() Index of column or parameter affected Access using public int getindex() Returns -1 if component unknown Indication of whether truncation was read or write Access using public boolean getread() Number of bytes that should have been transferred Access using public int getdatasize() Returns -1 if component unknown Number of bytes that were actually transferred Access using public int gettransfersize() Returns -1 if component unknown Link to next exception/warning object 14