JDBC. Dr. Jim Arlow Clear View Training Limited Clear View Training 2005 v1.3 1

Similar documents
SQL and Java. Database Systems Lecture 19 Natasha Alechina

CS/CE 2336 Computer Science II

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

The JAVA Way: JDBC and SQLJ

CS 377 Database Systems SQL Programming. Li Xiong Department of Mathematics and Computer Science Emory University

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

Why Is This Important? Database Application Development. SQL in Application Code. Overview. SQL in Application Code (Contd.

COSC344 Database Theory and Applications. Java and SQL. Lecture 12

Self-test Database application programming with JDBC

Supplement IV.D: Tutorial for MS Access. For Introduction to Java Programming By Y. Daniel Liang

JDBC (Java / SQL Programming) CS 377: Database Systems

CS2506 Operating Systems II Lab 8, 8 th Tue/03 /2011 Java API

Java DataBase Connectivity (JDBC)

Java Server Pages and Java Beans

Database Access Through Java Technologies

What is ODBC? Database Connectivity ODBC, JDBC and SQLJ. ODBC Architecture. More on ODBC. JDBC vs ODBC. What is JDBC?

Database Programming. Week *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford

1 SQL Data Types and Schemas

DEVELOPING MULTITHREADED DATABASE APPLICATION USING JAVA TOOLS AND ORACLE DATABASE MANAGEMENT SYSTEM IN INTRANET ENVIRONMENT

How To Use The Database In Jdbc.Com On A Microsoft Gdbdns.Com (Amd64) On A Pcode (Amd32) On An Ubuntu (Amd66) On Microsoft

DATABASDESIGN FÖR INGENJÖRER - 1DL124

Overview. Database Application Development. SQL in Application Code (Contd.) SQL in Application Code. Embedded SQL. Embedded SQL: Variables

LSINF1124 Projet de programmation

Performance Tuning for the JDBC TM API

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.

Applets, RMI, JDBC Exam Review

Java and Databases. COMP514 Distributed Information Systems. Java Database Connectivity. Standards and utilities. Java and Databases

Application Development A Cocktail of Java and MCP. MCP Guru Series Dan Meyer & Pramod Nair

Using Netbeans and the Derby Database for Projects Contents

Java and Microsoft Access SQL Tutorial

Database Application Development. Overview. SQL in Application Code. Chapter 6

SQL and programming languages

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

Supplement IV.C: Tutorial for Oracle. For Introduction to Java Programming By Y. Daniel Liang

Accesssing External Databases From ILE RPG (with help from Java)

Java DB Performance. Olav Sandstå Sun Microsystems, Trondheim, Norway Submission ID: 860

Brazil + JDBC Juin 2001, douin@cnam.fr

FileMaker 14. ODBC and JDBC Guide

JDBC. It is connected by the Native Module of dependent form of h/w like.dll or.so. ex) OCI driver for local connection to Oracle

To create a universal SQL client for accessing local or remote database ( 35.2). To execute SQL statements in a batch mode ( 35.3).

Part IV: Java Database Programming

CS346: Database Programming.

Statement Level Interface. Call Level Interface. Static SQL. Status. Connections. Transactions. To connect to an SQL database, use a connect statement

Chapter 1 JDBC: Databases The Java Way! What Is The JDBC? The JDBC Structure ODBC s Part In The JDBC Summary

TECH TUTORIAL: EMBEDDING ANALYTICS INTO A DATABASE USING SOURCEPRO AND JMSL

More SQL: Assertions, Views, and Programming Techniques

Abstract. Introduction. Web Technology and Thin Clients. What s New in Java Version 1.1

Package sjdbc. R topics documented: February 20, 2015

PHP Language Binding Guide For The Connection Cloud Web Services

public class ResultSetTable implements TabelModel { ResultSet result; ResultSetMetaData metadata; int num cols;

How To Use A Sas Server On A Java Computer Or A Java.Net Computer (Sas) On A Microsoft Microsoft Server (Sasa) On An Ipo (Sauge) Or A Microsas (Sask

Exploiting Java Technology with the SAS Software Barbara Walters, SAS Institute Inc., Cary, NC

Security Module: SQL Injection

Oracle to MySQL Migration

Using JML to protect Java code against SQL injection. Johan Janssen June 26, 2007

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

MAKING ORACLE AND SQLJ WORK FOR YOU John Jay King, King Training Resources

CS 3200 Topic Overview

An Oracle White Paper June Migrating Applications and Databases with Oracle Database 12c

Comparing the Effectiveness of Penetration Testing and Static Code Analysis

Making Oracle and JDBC Work For You

To Java SE 8, and Beyond (Plan B)

Microsoft SQL Server Features that can be used with the IBM i

CHAPTER 3. Relational Database Management System: Oracle. 3.1 COMPANY Database

Introduction Web Portal Main Page Group Management Create group Modify Group Member List... 5

The Data Access Handbook

Chapter 4: SQL. Schema Used in Examples

Version Overview. Business value

Java and RDBMS. Married with issues. Database constraints

FileMaker 11. ODBC and JDBC Guide

CA IDMS Server r17. Product Overview. Business Value. Delivery Approach

Using DOTS as Apache Derby System Test

CSc 230 Software System Engineering FINAL REPORT. Project Management System. Prof.: Doan Nguyen. Submitted By: Parita Shah Ajinkya Ladkhedkar

Enterprise Java. Where, How, When (and When Not) to Apply Java in Client/Server Business Environments. Jeffrey Savit Sean Wilcox Bhuvana Jayaraman

Customer Bank Account Management System Technical Specification Document

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

Database System Concepts

Applications of JAVA programming language to database management

How To Let A Lecturer Know If Someone Is At A Lecture Or If They Are At A Guesthouse

Working With Derby. Version 10.2 Derby Document build: December 11, 2006, 7:06:09 AM (PST)

Object Oriented Design with UML and Java. PART XVIII: Database Technology

A Brief Introduction to MySQL

Week 5: Embedded SQL. Embedded SQL 4. Application Program. Interactive vs. Non-Interactive SQL. Update Statements

IBM soliddb IBM soliddb Universal Cache Version 6.3. Programmer Guide SC

7 Web Databases. Access to Web Databases: Servlets, Applets. Java Server Pages PHP, PEAR. Languages: Java, PHP, Python,...

Web Programming with Java Servlets

Java Programming. JDBC Spring Framework Web Services

Database access and JDBC. Tecniche di Programmazione A.A. 2013/2014

Java (12 Weeks) Introduction to Java Programming Language

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Building Web Applications, Servlets, JSP and JDBC

A Generic Database Web Service

Using SQL Developer. Copyright 2008, Oracle. All rights reserved.

CHAPTER 5 INTELLIGENT TECHNIQUES TO PREVENT SQL INJECTION ATTACKS

Automatic generation of fully-executable code from the Domain tier of UML diagrams

FileMaker 8. Installing FileMaker 8 ODBC and JDBC Client Drivers

An Introduction to Application Security in J2EE Environments

Web Application Development on a Linux System With a DB2 Database By Alan Andrea

Strategic Procurement: The SAS Solution for Supplier Relationship Management Fritz Lehman, SAS Institute Inc., Cary, NC

Transcription:

JDBC Dr. Jim Arlow Clear View Training Limited www.clearviewtraining.com Clear View Training 2005 v1.3 1

Copyright notice This course is Copyright 2000 Clear View Training Limited. All rights reserved. Materials in this course may not be reproduced electronically or optically without express permission from the copyright holder. For reprint permissions, contact Jim.Arlow@clearviewtraining.com Clear View Training 2005 v1.3 2

What is JDBC Java Application or Applet JDBC RDBMS JDBC, often known as Java Database Connectivity, provides a Java API for updating and querying relational databases using Structured Query Language (SQL) JDBC is now at version 2.0, although many databases don t as yet support all of the JDBC 2.0 features! Clear View Training 2005 v1.3 3

The 4 step approach to JDBC Every JDBC program is made up of the following 4 steps: Open a connection to the DB Execute a SQL statement Process the result We ll look at each of the four steps in detail! Close the connection to the DB Clear View Training 2005 v1.3 4

Example JDBC program 1 import java.sql.*; 2 class SelectProducts 3 { 4 public static void main(java.lang.string[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 1. open connection to DB 2. execute SQL statement 3. process result 4. close connection to DB 9 Connection con = DriverManager.getConnection( "jdbc:db2:test", "db2admin", " db2admin " ); 10 Statement statement = con.createstatement( ); 11 ResultSet rs = statement.executequery("select NAME, PRICE FROM PRODUCT"); 12 while ( rs.next( ) ) 13 { 14 String name = rs.getstring( "NAME" ); 15 float price = rs.getfloat( "PRICE" ); 16 System.out.println("Name: "+name+", price: "+price); 17 } 18 statement.close( ); 19 con.close( ); 20 } 21 catch( Exception e ) { e.printstacktrace( ); } 22 } 23 } Clear View Training 2005 v1.3 5 1 2 3 4

Opening a connection to the DB There are two parts to this: loading a driver we need a driver to allow our Java program to talk to the DB opening the connection itself Clear View Training 2005 v1.3 6

Loading a driver The first step in using JDBC is to load a driver. Here are some examples: The IBM DB2 driver: Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); The SUN JDBC/ODBC Bridge driver: Class.forName( "sun.jdbc.jdbcodbcdriver" ); Clear View Training 2005 v1.3 7

There are 4 categories of driver Type 1 JDBC-ODBC Bridge (Native Code) provides a Java bridge to ODBC implemented in native code and requires some non-java software on the client Type 2 Native-API (Partly Java) uses native code to access the DB with a thin Java wrapper can crash the JVM Type 3 Net-protocol (All Java) defines a generic network protocol that interfaces with some middleware that accesses the DB Type 4 Native-protocol (All Java) written entirely in Java Clear View Training 2005 v1.3 8

Type 1 JDBC-ODBC Bridge SQL command Java application Type 1 JDBC/ODBC ODBC driver result set proprietary protocol Provides a Java bridge to ODBC Implemented in native code and requires some non- Java software on the client Not a mandatory component of the JDK, and is not automatically supported by Java run-time environments Only recommended for light use Clear View Training 2005 v1.3 9

Type 2 Native API SQL command Java application Type 2 JDBC driver Native database library result set proprietary protocol Converts JDBC commands into DBMS-specific native calls Implemented in native code and requires some non- Java software on the client Interfaces directly with the DB, so has performance advantages over Type 1 Clear View Training 2005 v1.3 10

Type 3 JDBC-Net drivers SQL command Java application Type 3 JDBC driver Middleware result set JDBC Driver proprietary protocol A three tier solution Allows pure Java clients Can change DBMS without affecting the client most flexible Clear View Training 2005 v1.3 11

Type 4 Native Protocol drivers SQL command using proprietary protocol Java application Type 4 Pure Java result set using proprietary protocol Native Protocol drivers communicate directly with the DB They convert JDBC commands directly into the DB s native protocol No additional transformation or middleware layers, therefore has high performance best performance Clear View Training 2005 v1.3 12

Making a connection Next, the driver must connect to the DBMS: 9 Connection con = DriverManager.getConnection( "jdbc:db2:test", "db2admin", " db2admin " ); DB URL login password optional The object con gives us an open database connection Clear View Training 2005 v1.3 13

Creating Statements A Statement object is used to send SQL statements to the DB First we get a Statement object from our DB connection con 10 Statement statement = con.createstatement( ); Clear View Training 2005 v1.3 14

Example creating a table 1 import java.sql.*; 2 class CreateProductTable 3 { 4 public static void main(java.lang.string[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 String url = "jdbc:db2:test"; 10 Connection con = DriverManager.getConnection( url, "db2admin", "db2admin" ); 11 Statement statement = con.createstatement(); 12 String createproducttable = "CREATE TABLE PRODUCT " + 13 "(NAME VARCHAR(64), " + 14 "ID VARCHAR(32) NOT NULL, " + 15 "PRICE FLOAT, " + 16 "DESC VARCHAR(256), " + 17 "PRIMARY KEY(ID))"; 18 statement.executeupdate( createproducttable ); 19 } catch( Exception e ) { e.printstacktrace(); } 20 } 21 } Clear View Training 2005 v1.3 15

executeupdate(string sql) Use the executeupdate() method of the Statement object to execute DDL and SQL commands that update a table (INSERT, UPDATE, DELETE): 12 String createproducttable = "CREATE TABLE PRODUCT " + 13 "(NAME VARCHAR(64), " + 14 "ID VARCHAR(32) NOT NULL, " + 15 "PRICE FLOAT, " + 16 "DESC VARCHAR(256), " + 17 "PRIMARY KEY(ID))"; 18 statement.executeupdate( createproducttable ); Be careful to always put spaces in the SQL string at the right places! Clear View Training 2005 v1.3 16

Example: inserting rows 1 import java.sql.*; 2 class InsertProducts 3 { 4 public static void main(java.lang.string[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 String url = "jdbc:db2:test"; 10 Connection con = DriverManager.getConnection( url, "db2admin", " db2admin " ); 11 Statement statement = con.createstatement(); 12 statement.executeupdate("insert INTO PRODUCT " + 13 "VALUES ( 'UML User Guide', " + 14 "'0-201-57168-4', 47.99, 'The UML user guide')" ); 15 statement.executeupdate("insert INTO PRODUCT " + 16 "VALUES ( 'Java Enterprise in a Nutshell', " + 17 "'1-56592-483-5', 29.95, 'A good introduction to J2EE')" ); 18 con.close(); 19 statement.close(); 20 }catch( Exception e ) { e.printstacktrace(); } 21 } 22 } Clear View Training 2005 v1.3 17

executequery(string sql) We use the executequery( ) method of the Statement object to execute a SQL statement that returns a single ResultSet: 11 ResultSet rs = statement.executequery("select NAME, PRICE FROM PRODUCT"); Typically, the SQL statement is a SQL SELECT executequery( ) always returns a ResultSet, never null. However, the ResultSet may be empty Clear View Training 2005 v1.3 18

Example: selecting rows 1 import java.sql.*; 2 class SelectProducts 3 { 4 public static void main(java.lang.string[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 Connection con = DriverManager.getConnection( "jdbc:db2:test", "db2admin", " db2admin " ); 10 Statement statement = con.createstatement(); 11 ResultSet rs = statement.executequery("select NAME, PRICE FROM PRODUCT"); 12 while ( rs.next( ) ) 13 { 14 String name = rs.getstring( "NAME" ); 15 float price = rs.getfloat( "PRICE" ); 16 System.out.println("Name: "+name+", price: "+price); 17 } 18 statement.close(); 19 con.close(); 20 } catch( Exception e ) { e.printstacktrace(); } 21 } 22 } Clear View Training 2005 v1.3 19

ResultSet ResultSet objects provide access to a table usually they provide access to the pseudo table that is the result of a SQL query ResultSet objects maintain a cursor pointing to the current row of data this cursor initially points before the first row and is moved to the first row by the next() method 11 ResultSet rs = statement.executequery("select NAME, PRICE FROM PRODUCT"); 12 while ( rs.next( ) ) 13 { 14 String name = rs.getstring( "NAME" ); 15 float price = rs.getfloat( "PRICE" ); 16 System.out.println("Name: "+name+", price: "+price); 17 } Clear View Training 2005 v1.3 20

JDBC 2.0 Types of ResultSet Statement statement = con.createstatement( type, concurrency); Depending on the parameters passed into the Connection.createStatement( ) method, we can get a total of 6 different types of ResultSet returned! Passing no arguments to createstatement() gives a default forward-only read-only ResultSet We ll look at the possible values for type and concurrency next Clear View Training 2005 v1.3 21

JDBC 2.0 type type = ResultSet.TYPE_SCROLL_SENSITIVE ResultSet.TYPE_SCROLL_INSENSITIVE ResultSet.TYPE_FORWARD_ONLY semantics Scrollable. Reflects changes made to the underlying data Scrollable. Does not reflect changes made to the underlying data Not scrollable. Does not reflect changes made to the underlying data N.B. Scrollable means that we can navigate forwards and backwards through the ResultSet Clear View Training 2005 v1.3 22

JDBC 2.0 concurrency concurrency = semantics ResultSet.CONCUR_READ_ONLY ResultSet.CONCUR_UPDATABLE the ResultSet may not be updated the ResultSet may be updated Clear View Training 2005 v1.3 23

getxxx( ) methods see notes! The ResultSet has a wide range of methods to return SQL types such as VARCHAR as equivalent Java types For example rs.getstring( NAME ) returns the product name as a String in fact, we can get any of the SQL types with getstring( ) and it will automatically be converted to a String The getxxx( ) methods can take a column name or the number of the column column numbers start at 1 and go from left to right Clear View Training 2005 v1.3 24

JDBC 2.0 ResultSet navigation methods Method first() last() next() previous() beforefirst() afterlast() absolute(int) relative(int) Moves cursor to first row Moves cursor to last row Moves cursor to next row Moves cursor to previous row Semantics Moves cursor to just before the first row Moves cursor to just after the last row Moves cursor to a row index. If positive counting from the front, if negative from the back Moves cursor a relative number of rows, positive or negative from the current position Clear View Training 2005 v1.3 25

Working with ResultSets We can limit the number of rows that a ResultSet can contain by using: Statement statement = con.createstatement(); statement.setmaxrows(100); If a Statement returns multiple ResultSets, then we can move to the next ResultSet as follows: while ( statement.getmoreresults() ) { rs = statement. getresultset(); Clear View Training 2005 v1.3 26

JDBC 2.0 Updateable ResultSet If the statement is created to be of type ResultSet.CONCUR_UPDATABLE, then we may be able to update the database by modifying the ResultSet itself this may not be supported by all DBMSs as it is not a mandatory requirement for JDBC 2.0 compatibility Clear View Training 2005 v1.3 27

JDBC 2.0 updatexxx( ) methods Like the getxxx( ) methods, the ResultSet has a wide range of updatexxx( ) methods to change the value of SQL types in the ResultSet For example rs.updatestring( PRICE, 40.0F) changes the price of a product we have to be very careful that that all the types in an update expression match The updatexxx( ) methods can take a column name or the number of the column column numbers start at 1 and go from left to right Clear View Training 2005 v1.3 28

JDBC 2.0 Updating a row This is a three step procedure: navigate to the appropriate row using a SELECT and ResultSet navigation methods update the field values in the ResultSet write the change back to the DB rs.first(); rs.updatefloat("price", 40.0F); rs.updaterow(); Clear View Training 2005 v1.3 29

JDBC 2.0 Inserting a row This is a three step procedure: navigate to insert row update the field values in the ResultSet write the row to the DB rs.movetoinsertrow(); rs.updatestring("name", "UML Distilled"); rs.updatestring("id", "0-201-32563-2"); rs.updatefloat("price", 40.0F); rs.insertrow(); Clear View Training 2005 v1.3 30

JDBC 2.0 Deleting a row This is a simple two step procedure: navigate to row to be deleted delete the row rs.last(); rs.deleterow(); Clear View Training 2005 v1.3 31

Prepared statements If we want to execute the same SQL statement several times, we can create a PreparedStatement object: at the point of creation of a PreparedStatement object the SQL code is sent to the DB and compiled. Subsequent executions may therefore be more efficient than normal statements PreparedStatements can take parameters Clear View Training 2005 v1.3 32

Prepared statement example 1 import java.sql.*; 2 class PreparedStatementTest 3 { 4 public static void main(java.lang.string[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 Connection con = DriverManager.getConnection( "jdbc:db2:test", "db2admin", " db2admin " ); 10 PreparedStatement findbooks = con.preparestatement( 11 "SELECT NAME FROM PRODUCT WHERE NAME LIKE? " ); 12 findbooks.setstring( 1, "%Java%" ); 13 ResultSet rs = findbooks.executequery(); 14 while ( rs.next() ) 15 { System.out.println("Name: "+ rs.getstring( "NAME" ) ); } 16 findbooks.setstring( 1, "%UML%" ); 17 rs = findbooks.executequery(); 19 while ( rs.next() ) 20 { System.out.println("Name: "+ rs.getstring( "NAME" ) ); } 21 findbooks.close(); 22 con.close(); 23 } catch( Exception e ) { e.printstacktrace(); } 24 } 25 } Clear View Training 2005 v1.3 33

Transactions Normally each SQL statement will be committed automatically when it has completed executing (auto commit is on) A group of statements can be committed together by turning auto commit off, and explicitly committing the statements ourselves This ensures that if any of the statements fail, they all fail. We can then roll back the transaction Clear View Training 2005 v1.3 34

JDBC transaction modes TRANSACTION_NONE con.settransactionisolation( mode ) transactions are disabled or not supported TRANSACTION_READ_UNCOMITTED other transactions may see the results before the transaction is committed dirty read - uncommitted rows might be rolled back if the transaction fails. TRANSACTION_READ_COMMITTED dirty reads are not allowed. TRANSACTION_REPEATABLE_READ if a transaction performs multiple reads on a row that is being changed by another transaction, then it does not see the changes TRANSACTION_SERIALIZABLE same as TRANSACTION_REPEATABLE_READ but also protects against row insertions if a transaction does a read, another transaction inserts a row, and the first transaction does another read, the first transaction does not see the new row. Clear View Training 2005 v1.3 35

Transaction example 1 import java.sql.*; 2 class TransactionTest 3 { 4 public static void main(java.lang.string[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 String url = "jdbc:db2:test"; 10 Connection con = DriverManager.getConnection( url, "db2admin", "db2admin" ); 11 Statement s = con.createstatement(); 12 try 13 { 14 con.setautocommit( false ); 15 s.executeupdate("update PRODUCT SET PRICE = 40.00 WHERE ID = '0-201-57168-4' " ); 16 s.executeupdate( 17 "UPDATE REVIEW SET COMMENT = 'Now on sale!' WHERE BOOKID = '0-201-57168-4' " ); 18 con.commit(); 19 }catch( SQLException e ) { con.rollback(); } 20 finally{ con.close(); s.close(); } 21 }catch( Exception e ){ e.printstacktrace(); } 22 } 23 } Clear View Training 2005 v1.3 36

JDBC 2.0 Batch updates JDBC 1.0 was very inefficient for loading a lot of data into a DB - a separate SQL command had to be executed for each record changed JDBC 2.0 allows batch updates multiple statements can be executed as a single batch we can roll back the whole batch if a single statement fails We simply add statements to be batched to a Statement or PreparedStatement object using addbatch()! We can remove the statements using clearbatch() Clear View Training 2005 v1.3 37

JDBC 2.0 Batch update example 1 import java.sql.*; 2 class BatchInsertProducts 3 { 4 public static void main(java.lang.string[ ] args) throws SQLException, ClassNotFoundException 5 { 6 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 7 String url = "jdbc:db2:test"; 8 Connection con = DriverManager.getConnection( url, "db2admin", "db2admin" ); 9 Statement s = con.createstatement(); 10 try 11 { 12 con.setautocommit( false ); 13 s.addbatch("insert INTO PRODUCT " + "VALUES ( 'The Object Constraint Language', " + 15 "'0-201-37940-4', 29.95, 'All about constraints')" ); 16 s.addbatch("insert INTO PRODUCT " + "VALUES ( 'The Rational Unified Process', " + 18 "'0-201-60459-0',29.95, 'A good introduction to RUP')" ); 19 int[ ] count = s.executebatch( ); 20 con.commit( ); 21 22 }catch( SQLException e ) { con.rollback( ); } 23 finally{ con.close( ); s.close( ); } 24 } 25 } Clear View Training 2005 v1.3 38

Stored procedures The syntax for defining a stored procedure is different for each DBMS use the stored procedure tools that come with the RDBMS The syntax for calling a stored procedure is different for each DBMS JDBC defines a special escape sequence syntax that allows stored procedures to be called in the same way on any RDBMS Clear View Training 2005 v1.3 39

Escape sequences {?= call <procedure-name>(<arg1>,<arg2>, )} {call <procedure-name>(<arg1>,<arg2>, )} The? represents a return value <procedure-name> is the name of the stored procedure <arg1> etc. are the arguments passed into and out of the stored procedure Clear View Training 2005 v1.3 40

Stored procedure example 1 import java.sql.*; 2 class StoredProcedureExample 3 { 4 public static void main(java.lang.string[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 Connection con = DriverManager.getConnection( "jdbc:db2:test", "db2admin", " db2admin " ); 10 CallableStatement cs = con.preparecall("{call DB2ADMIN.ALLPRODUCTS}"); 11 cs.execute(); 12 ResultSet rs = cs.getresultset(); 13 while ( rs.next() ) 14 { 15 String name = rs.getstring( "NAME" ); 16 float price = rs.getfloat( "PRICE" ); 17 System.out.println("Name: "+name+", price: "+price); 18 } 19 con.close(); 20 cs.close(); 21 }catch( Exception e ){ e.printstacktrace(); } 22 } 23 } create a callable statement Clear View Training 2005 v1.3 41

Using input parameters 1 import java.sql.*; 2 class StoredProcedureParameterExample 3 { 4 public static void main(java.lang.string[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 Connection con = DriverManager.getConnection( "jdbc:db2:test", "db2admin", "db2admin" ); 10 CallableStatement cs = con.preparecall("{call DB2ADMIN.FINDPROD2(?)}"); 11 cs.setstring( 1, "%UML%" ); 12 cs.execute(); 13 ResultSet rs = cs.getresultset(); 14 while ( rs.next() ) 15 { 16 String name = rs.getstring( "NAME" ); 17 float price = rs.getfloat( "PRICE" ); 18 System.out.println("Name: "+name+", price: "+price); 19 } 20 con.close(); 21 cs.close(); 22 }catch( Exception e ){ e.printstacktrace(); } 23 } 24 } set the parameter value we specify a single parameter Clear View Training 2005 v1.3 42

Metadata JDBC has facilities to get information about a ResultSet or DB for a ResultSet, this information may include the number and names of the columns, the types of the columns etc. for a DB this information may include the name of the driver, the DB URL etc. This information about a ResultSet or DB is known as metadata See the following classes for details: ResultSet see ResultSetMetadata Database see DatabaseMetadata Clear View Training 2005 v1.3 43

Getting metadata Getting database metadata: Connection con = DriverManager.getConnection( "jdbc:db2:test", "db2admin", "db2admin" ); DatabaseMetaData dmd = con.getmetadata( ); Getting ResultSet metadata: Statement statement = con.createstatement(); ResultSet rs = statement.executequery("select NAME, PRICE FROM PRODUCT"); ResultSetMetaData rsmd = rs.getmetadata( ); Clear View Training 2005 v1.3 44

Summary We have looked at: 4 step approach to JDBC Connection drivers Statement PreparedStatement batch update transactions CallableStatement (stored procedures) ResultSet handling Metadata Clear View Training 2005 v1.3 45

Appendix: IBM DB2 (v6) Clear View Training 2005 v1.3 46

Installing the JDBC 2.0 driver To install JDBC 2.0: go to the directory sqllib\java12 run the command usejdbc2 To switch back to 1.2.2: go to the directory sqllib\java12 run the command usejdbc1 Clear View Training 2005 v1.3 47