Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CSE5200 JDBC and JDeveloper JDBC java.sql package java.sql classes.

Similar presentations

Presentation on theme: "1 CSE5200 JDBC and JDeveloper JDBC java.sql package java.sql classes."— Presentation transcript:

1 1 CSE5200 JDBC and JDeveloper JDBC java.sql package java.sql classes

2 2 References Orfali, Harkey & Evans Client Server Survival Guide (3rd ed) 1999 Ch.11 p.237-249 Orfali, R. and Harkey, D (1998) Client/Server Programming with JAVA and CORBA (2nd Ed.) Wiley Ch. 23, 25

3 3 JDBC SQL database access is the most prevalent client/server application model –I.e these are the services we require most JDBC – is the Java object version of Microsoft ODBC –defines Java class wrappers for SQL database access –can access almost any database service –JDBC drivers are available from almost any Java vendor –java.sql.* package is now part of the Java core

4 4 JDBC –compliance means the drivers support SQL92 –must implement the java.sql.* classes –must be thread safe JDBC Naming Convention jdbc:oracle:oci7:@db", "scott", "tiger” subprotocolthis could be a URL JDBC Classes –JDBC Core Interfaces –Java Language extensions –Java Utility Extensions –SQL Metadata Interfaces

5 5 JDBC Core Classes –locate DBMS drivers - DriverManagerClass locates the driver for DB you specify –establish connections commit, rollback and the DB isolation level –submit SQL statements 2 extensions –Prepared statement - precompile and execute –Callable statement - stored procedures –process result set manipulate the cursor and get back results

6 6 Java.sql.* Oracle extensions - the Oracle JDBC classes contained in the file - contain a set of classes that invoke the core classes contained in the java.sql.* package the java.sql.* package was not part of the core classes in JDK 1.0

7 7 JDBC Drivers

8 8 Typical Steps Import the JDBC Package Set useful static class variables for driver, DBMS URI, credentials, etc. Register appropriate driver with the DriverManager class Set connection Properties (typically credentials) Invoke the Connection Create SQL statement in a String Invoke Statement on connection Execute SQL statement via appropriate method on Statement object (PTO)

9 9 Typical Steps  execute(...), executeQuery(...) for SEL, receive ResultSet/s  executeUpdate(...) for INS/DEL/UPD or DDLs, receive integer value indicating row count  automatic commit, unless disabled, in which case an explicit COMMIT must be executed to save changes to database Check for Exceptions Process ResultSet  NB: Columns numbered from 1. Close ResultSet and Statement  Unless multiple transactions, then redefine and reuse Cycle for further operations Close Connection

10 10 Registering & Connecting: The DriverManager Class oracle.jdbc.driver (classes to support database access and updates in Oracle type formats) // Load the Oracle JDBC driver DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); or Class.forName ("oracle.jdbc.driver.OracleDriver"); // Connect to the database Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@CSE5200A", “S1234567", “student");

11 11 Sample Code Code for creating a connection using JDBC with Oracle try { // register the driver to connect to oracle DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); // db_con is a connection object that lets us connect to the // database with specified URL/userid/password Connection db_con = DriverManager.getConnection ("", "studentid", "password"); System.out.println("Connection Success"); } catch(SQLException f) { // gives error if the above did not succeed. System.out.println("Connection Failed. SQL Exception"); }

12 12 Code to retrieve data from the Database using the previously created JDBC Connection object try { // statement object stmt created to execute queries using db_con Statement stmt = db_con.createStatement(); // rset is an object that holds the result of the query ResultSet rset = stmt.executeQuery ("SELECT * FROM authors"); // looping through the resultset object till end while ({ // getString gets the string data in col 1 of result // and we would have rset.getInt(2) if col 2 was an integer System.out.println (rset.getString(1)); } } catch(SQLException f) { // error handling for above System.out.println("Cannot retrieve data SQL Exception occured"); }

13 13 Transactions: The Connection Interface Connection Interface –Session between application and database –Specified by location (URI) and credentials Commit/Rollback –conn.commit(); –conn.rollback(); Ignore Isolation Levels Set Autocommit off –after connect but before any statement conn.setAutoCommit (false);

14 14 Creating a Statement Object: Connection Interface Statement stmt = conn.createStatement (); stmt.execute (“select empno from emp”); –no parameters PreparedStatement pmst = conn.prepareStatement (“insert into emp (EMPNO, EMPNAME) values (?, ?)”); - setting and getting parameters next slide pstmt.execute(); selectText = "SELECT firstname,lastname FROM addresses"; Statement selectStmt = dbConnection.createStatement(); ResultSet result = selectStmt.executeQuery(selectText); insertText = "INSERT INTO addresses VALUES (1,'John','Smith')"; Statement insertStmt = dbConnection.createStatement(); int rowsInserted = insertStmt.executeUpdate(insertText);

15 15 Setting Parameters & Getting Fields PreparedStatement  statement is pre-compiled and stored in a PreparedStatement object. Can use this to efficiently execute the statement multiple times  allows IN parameters within the query  referenced by number  setXXX () methods used setXXX(); –pstmt.setString (1, "SCOTT"); getXXX(); –System.out.println( rset.getString (1) ); setNULL(); - don’t use nulls

16 16 ResultSet Interface Provides access to a table of data generated by executing a Statement Table rows are retrieved in sequence via a cursor pointing to the current row of data Some methods:  next ()  getXXX () methods  wasNull ()—detect SQL NULL values  close ()

17 17 Executing a Query and Returning the ResultSet ResultSet Interface ResultSet rset = stmt.executeQuery ("SELECT ename FROM emp"); executeUpdate –insert, delete, update execute(): while ( System.out.println (rset.getString(1)); This is standard JDBC syntax. The next() method returns false when it reaches the end of the result set. The employee names are materialized as JavaStrings.

18 18 Closing the ResultSet, Statement and Connection You must explicitly close the ResultSet and Statement objects after you finish using them. rset.close(); stmt.close(); You must close your connection to the database once you finish your work. conn.close();

19 19 ResultSet Interface void dispResultSet (ResultSet rs) throws SQLException { while ( ()) { System.out.print ("" + rs.getInt (1)) String firstName = rs.getString ("FIRST_NAME"); System.out.print (rs.wasNull () ? “[no first name]” : firstName); System.out.print (rs.getString ("LAST_NAME")); System.out.println (rs.getDate (4)); } rs.close (); }

20 20 SQLException getMessage(): returns the error message associated with the object that threw the exception printStackTrace(): prints this object name and its stacktrace to the specified print stream This example uses both getMessage() and printStackTrace() to return errors. catch(SQLException e); { System.out.println("exception: " + e.getMessage()); e.printStackTrace(); } OR

21 21 SQL Exception continued catch (SQLException e) { while(e != null) { System.out.println(e.getMessage()); e = e.getNextException(); password = readEntry ("hold it: "); }

22 22 SQLJ Overview Embedding SQL statements into a host language - Java Opposed to a CLI to access the database - JDBC SQLJ is similar to the ANSI/ISO embedded SQL standards for C, Fortran and other programming languages –proposed to ANSI/ISO as the SQL and Java Standard –(ANSI x.3.135.10-1998) In Oracle terms Pro*Java Created by IBM, Oracle, Sybase and Tandem because –OO languages have better type checking –no need for writing a dynamic component because JDBC already exists

23 23 SQLJ Architecture *.SQLJ Oracle SQLJ translator *.JAVA Oracle Customiser Java Byte Code Java Compiler JAVAC Run Oracle sqlj MyFile.sqlj MyOtherFile.sqlj

24 24 SQLJ Runtime Configuration SQLJ Application SQLJ Runtime Lib Javasoft ODBC based drivers Oracle JDBC/OCI drivers Oracle thin JDBC driver ODBC C Library OCI C Library Java sockets

Download ppt "1 CSE5200 JDBC and JDeveloper JDBC java.sql package java.sql classes."

Similar presentations

Ads by Google