16 Copyright © 2005, Oracle. All rights reserved. Using JDBC to Access the Database.

Slides:



Advertisements
Similar presentations
Using the SQL Access Advisor
Advertisements

Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
Author: Julia Richards and R. Scott Hawley
Communicating in J2EE.
19 Copyright © 2005, Oracle. All rights reserved. Distributing Modular Applications: Developing Web Services.
21 Copyright © 2005, Oracle. All rights reserved. Oracle Application Server 10g Transaction Support.
1 Copyright © 2005, Oracle. All rights reserved. Introduction.
Preface IIntroduction Objectives I-2 Course Overview I-3 1Introducing the Java and Oracle Platforms Objectives 1-2 What Is Java? 1-3 Key Benefits of Java.
5 Copyright © 2005, Oracle. All rights reserved. Accessing the Database with Servlets.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
11 Copyright © 2005, Oracle. All rights reserved. Creating the Business Tier: Enterprise JavaBeans.
3 Copyright © 2005, Oracle. All rights reserved. Basic Java Syntax and Coding Conventions.
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
15 Copyright © 2005, Oracle. All rights reserved. Container-Managed Relationships (CMRs)
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
9 Copyright © 2005, Oracle. All rights reserved. Modularizing JavaServer Pages Development with Tags.
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
J2EE Overview.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
6 Copyright © 2005, Oracle. All rights reserved. Building Applications with Oracle JDeveloper 10g.
17 Copyright © 2005, Oracle. All rights reserved. Deploying Applications by Using Java Web Start.
1 RA I Sub-Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Casablanca, Morocco, 20 – 22 December 2005 Status of observing programmes in RA I.
Custom Statutory Programs Chapter 3. Customary Statutory Programs and Titles 3-2 Objectives Add Local Statutory Programs Create Customer Application For.
13 Copyright © 2005, Oracle. All rights reserved. Monitoring and Improving Performance.
Displaying Data from Multiple Tables
8 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Using Explicit Cursors.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
1..
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
CE203 - Application Programming Autumn 2013CE203 Part 51 Part 5.
Analyzing Genes and Genomes
Essential Cell Biology
PSSA Preparation.
Essential Cell Biology
Immunobiology: The Immune System in Health & Disease Sixth Edition
Energy Generation in Mitochondria and Chlorplasts
Java II--Copyright © Tom Hunter. Chapter 18 JDBC.
Copyright  Oracle Corporation, All rights reserved. 2 Java and Databases: An Overview.
1 JDBC Java Database Connectivity. 2 c.pdf
JDBC / ODBC JDBC is the java API that facilitate interaction of a java application with the DBMS. FIRST APPROACH:
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Overview of JDBC and Pro*C 1 Overview of JDBC,Pro*C and Oracle connectivity on Omega CSE 5330 – Database Systems.
Active Server Pages ASP is Microsoft’s server-side script engine for dynamically-generated web pages. Most common language used is VBScript. If you use.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
Copyright  Oracle Corporation, All rights reserved. 7 Accessing a Database Using SQLJ.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
Chapter 17 Accessing Databases with JDBC. JDBC JDBC provides a standard library for accessing relational databases. By using the JDBC API, you can access.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
16 Java Database Connectivity. 2 Understand the JDBC Understand the steps of the JDBC: 1.) Importing packages 2.) Opening a connection to a database 3.)
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
JDBC (Java Database Connectivity)
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
1 JDBC – Java Database Connectivity CS , Spring 2010.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Using JDBC to Access the Database
JDBC – Java Database Connectivity
Interacting with Database
JDBC Example.
Presentation transcript:

16 Copyright © 2005, Oracle. All rights reserved. Using JDBC to Access the Database

16-2 Copyright © 2005, Oracle. All rights reserved. Objectives After completing this lesson, you should be able to do the following: Describe how Java applications connect to the database Describe how Java database functionality is supported by the Oracle database Load and register a JDBC driver Connect to an Oracle database Follow the steps to execute a simple SELECT statement Map simple Oracle database types to Java types

16-3 Copyright © 2005, Oracle. All rights reserved. Java, J2EE, and Oracle 10g Oracle database Web server Client Application server Presentation Business logic Data Oracle Application Server 10g J2EE Certified Environment JDBC

16-4 Copyright © 2005, Oracle. All rights reserved. Client application or applet Connecting to a Database with Java Client applications, JSPs, and servlets use JDBC. JDBCRelational DB

16-5 Copyright © 2005, Oracle. All rights reserved. JDBC is a standard interface for connecting to relational databases from Java. –The JDBC API includes Core API Package in java.sql. –JDBC 2.0 API includes Optional Package API in javax.sql. –JDBC 3.0 API includes the Core API and Optional Package API Include the Oracle JDBC driver archive file in the CLASSPATH. The JDBC class library is part of the Java 2, Standard Edition (J2SE). What Is JDBC?

16-6 Copyright © 2005, Oracle. All rights reserved. // Standard packages import java.sql.*; import java.math.*; // optional // Oracle extension to JDBC packages import oracle.jdbc.*; import oracle.sql.*; Preparing the Environment Set the CLASSPATH : Import JDBC packages: [Oracle Home]\jdbc\lib\classes12.jar

16-7 Copyright © 2005, Oracle. All rights reserved. Notes Page

16-8 Copyright © 2005, Oracle. All rights reserved. Steps for Using JDBC to Execute SQL Statements 1. Register JDBC driver. 4. Execute SQL statement. 4a. Process SELECT statement. 4b. Process DML or DDL statement. 6. Close connections.5. Process query results. 3. Create statement object. 2. Obtain a connection.

16-9 Copyright © 2005, Oracle. All rights reserved. Step 1: Registering the Driver Register the driver in the code: – DriverManager.registerDriver (new oracle.jdbc.OracleDriver()); – Class.forName ("oracle.jdbc.OracleDriver"); Register the driver when launching the class: – java –D jdbc.drivers = oracle.jdbc.OracleDriver ;

16-10 Copyright © 2005, Oracle. All rights reserved. Using the package oracle.jdbc.driver, Oracle provides different drivers to establish a connection to the database. JDBC calls Database commands Database Connecting to the Database OracleDriver Thin client OCI Server-based …

16-11 Copyright © 2005, Oracle. All rights reserved. Client Oracle JDBC Drivers: Thin Client Driver Is written entirely in Java Must be used by applets Server Oracle Applet JDBC Thin driver

16-12 Copyright © 2005, Oracle. All rights reserved. Application JDBC OCI driver Oracle JDBC Drivers: OCI Client Drivers Is written in C and Java Must be installed on the client ClientServer Oracle ocixxx.dll

16-13 Copyright © 2005, Oracle. All rights reserved. Choosing the Right Driver Applet Client application EJB, servlet (on the middle tier) Stored procedure OCIThin Driver Thin Server side OCI Thin Type of Program

16-14 Copyright © 2005, Oracle. All rights reserved. Step 2: Getting a Database Connection In JDBC 1.0, use the DriverManager class, which provides overloaded getConnection() methods. –All connection methods require a JDBC URL to specify the connection details. Example: Vendors can provide different types of JDBC drivers. Connection conn = DriverManager.getConnection( "scott","tiger");

16-15 Copyright © 2005, Oracle. All rights reserved. About JDBC URLs JDBC uses a URL-like string. The URL identifies –The JDBC driver to use for the connection –Database connection details, which vary depending on the driver used Example using Oracle Thin JDBC driver: – jdbc: : jdbc:oracle: ProtocolDatabase identification

16-16 Copyright © 2005, Oracle. All rights reserved. JDBC URLs with Oracle Drivers Oracle Thin driver Oracle OCI driver Syntax: : : Example: Syntax: Example:

16-17 Copyright © 2005, Oracle. All rights reserved. Step 3: Creating a Statement JDBC statement objects are created from the Connection instance: Use the createStatement() method, which provides a context for executing an SQL statement. Example: Connection conn = DriverManager.getConnection( "scott","tiger"); Statement stmt = conn.createStatement();

16-18 Copyright © 2005, Oracle. All rights reserved. Using the Statement Interface The Statement interface provides three methods to execute SQL statements: Use executeQuery(String sql) for SELECT statements. –Returns a ResultSet object for processing rows Use executeUpdate(String sql) for DML or DDL. –Returns an int Use execute(String) for any SQL statement. –Returns a boolean value

16-19 Copyright © 2005, Oracle. All rights reserved. Step 4a: Executing a Query Provide a SQL query string, without semicolon, as an argument to the executeQuery() method. Returns a ResultSet object: Statement stmt = null; ResultSet rset = null; stmt = conn.createStatement(); rset = stmt.executeQuery ("SELECT ename FROM emp");

16-20 Copyright © 2005, Oracle. All rights reserved. The ResultSet Object The JDBC driver returns the results of a query in a ResultSet object. ResultSet : –Maintains a cursor pointing to its current row of data –Provides methods to retrieve column values

16-21 Copyright © 2005, Oracle. All rights reserved. Step 4b: Submitting DML Statements 1. Create an empty statement object: 2. Use executeUpdate to execute the statement: Example: Statement stmt = conn.createStatement(); int count = stmt.executeUpdate(SQLDMLstatement); Statement stmt = conn.createStatement(); int rowcount = stmt.executeUpdate ("DELETE FROM order_items WHERE order_id = 2354");

16-22 Copyright © 2005, Oracle. All rights reserved. 1. Create an empty statement object: 2. Use executeUpdate to execute the statement: Example: Statement stmt = conn.createStatement(); int rowcount = stmt.executeUpdate ("CREATE TABLE temp (col1 NUMBER(5,2), col2 VARCHAR2(30)"); Step 4b: Submitting DDL Statements Statement stmt = conn.createStatement(); int count = stmt.executeUpdate(SQLDDLstatement);

16-23 Copyright © 2005, Oracle. All rights reserved. Step 5: Processing the Query Results The executeQuery() method returns a ResultSet. Use the next() method in loop to iterate through rows. Use getXXX() methods to obtain column values by column position in query, or column name. stmt = conn.createStatement(); rset = stmt.executeQuery( "SELECT ename FROM emp"); while (rset.next()) { System.out.println (rset.getString("ename")); }

16-24 Copyright © 2005, Oracle. All rights reserved. Step 6: Closing Connections Explicitly close a Connection, Statement, and ResultSet object to release resources that are no longer needed. Call their respective close() methods: Connection conn =...; Statement stmt =...; ResultSet rset = stmt.executeQuery( "SELECT ename FROM emp");... // clean up rset.close(); stmt.close(); conn.close();...

16-25 Copyright © 2005, Oracle. All rights reserved. A Basic Query Example import java.sql.*; class TestJdbc { public static void main (String args [ ]) throws SQLException { DriverManager.registerDriver (new oracle.jdbc.OracleDriver()); Connection conn = DriverManager.getConnection "tiger"); Statement stmt = conn.createStatement (); ResultSet rset = stmt.executeQuery ("SELECT ename FROM emp"); while (rset.next ()) System.out.println (rset.getString ("ename")); rset.close(); stmt.close(); conn.close(); } }

16-26 Copyright © 2005, Oracle. All rights reserved. ResultSet rset = stmt.executeQuery ("SELECT empno, hiredate, job FROM emp"); while (rset.next()){ int id = rset.getInt(1); Date hiredate = rset.getDate(2); String job = rset.getString(3); Mapping Database Types to Java Types ResultSet maps database types to Java types: Column Name empno hiredate job Type NUMBER DATE VARCHAR2 Method getInt() getDate() getString()

16-27 Copyright © 2005, Oracle. All rights reserved. Notes Page

16-28 Copyright © 2005, Oracle. All rights reserved. 1.Create an empty statement object: 2.Use execute to execute the statement: 3.Process the statement accordingly: boolean isQuery = stmt.execute(SQLstatement); if (isQuery) { // was a query - process results ResultSet r = stmt.getResultSet();... } else { // was an update or DDL - process result int count = stmt.getUpdateCount();... } Handling an Unknown SQL Statement Statement stmt = conn.createStatement();

16-29 Copyright © 2005, Oracle. All rights reserved. SQL statements can throw a java.sql.SQLException. Use standard Java error handling methods. Handling Exceptions try { rset = stmt.executeQuery("SELECT empno, ename FROM emp"); } catch (java.sql.SQLException e) {... /* handle SQL errors */ }... finally { // clean up try { if (rset != null) rset.close(); } catch (Exception e) {... /* handle closing errors */ }...

16-30 Copyright © 2005, Oracle. All rights reserved. Managing Transactions By default, connections are in autocommit mode. Use conn.setAutoCommit(false) to turn autocommit off. To control transactions when you are not in autocommit mode, use: – conn.commit() : Commit a transaction – conn.rollback() : Roll back a transaction Closing a connection commits the transaction even with the autocommit off option.

16-31 Copyright © 2005, Oracle. All rights reserved. The PreparedStatement Object A PreparedStatement prevents reparsing of SQL statements. Use this object for statements that you want to execute more than once. A PreparedStatement can contain variables that you supply each time you execute the statement.

16-32 Copyright © 2005, Oracle. All rights reserved. PreparedStatement pstmt = conn.prepareStatement ("UPDATE emp SET ename = ? WHERE empno = ?"); PreparedStatement pstmt = conn.prepareStatement ("SELECT ename FROM emp WHERE empno = ?"); How to Create a PreparedStatement 1.Register the driver and create the database connection. 2.Create the PreparedStatement, identifying variables with a question mark (?):

16-33 Copyright © 2005, Oracle. All rights reserved. 1.Supply values for the variables: 2.Execute the statement: pstmt.setXXX(index, value); pstmt.executeQuery(); pstmt.executeUpdate(); int empNo = 3521; PreparedStatement pstmt = conn.prepareStatement("UPDATE emp SET ename = ? WHERE empno = ? "); pstmt.setString(1, "DURAND"); pstmt.setInt(2, empNo); pstmt.executeUpdate(); How to Execute a PreparedStatement

16-34 Copyright © 2005, Oracle. All rights reserved. Maximize Database Access Use connection pooling to minimize the operation costs of creating and closing sessions. Use explicit data source declaration for physical reference to the database. Use the getConnection() method to obtain a logical connection instance.

16-35 Copyright © 2005, Oracle. All rights reserved. Database Database commands Data source ConnectionPoolDataSource Java servlet Middle-tier server code Middle tier Connection Pooling JDBC driver

16-36 Copyright © 2005, Oracle. All rights reserved. Notes Page

16-37 Copyright © 2005, Oracle. All rights reserved. Notes Page

16-38 Copyright © 2005, Oracle. All rights reserved. Summary In this lesson, you should have learned the following: JDBC provides database connectivity for various Java constructs, including servlets and client applications. JDBC is a standard Java interface and part of the J2SE. The steps for using SQL statements in Java are Register, Connect, Submit, and Close. SQL statements can throw exceptions. You can control default transactions behavior.

16-39 Copyright © 2005, Oracle. All rights reserved. Practice 16: Overview This practice covers: Setting up the Java environment for JDBC Adding JDBC components to query the database Populating the OrderEntryFrame with Customers from the database

16-40 Copyright © 2005, Oracle. All rights reserved. Notes Page for Practice 16

16-41 Copyright © 2005, Oracle. All rights reserved. Practice 16: Notes

16-42 Copyright © 2005, Oracle. All rights reserved. Practice 16: Notes