Introduction to JDBC - George Masonoffutt/classes/642/slides/642Lec08a-JDBC.pdf · Introduction to...

Post on 06-Feb-2018

226 views 3 download

Transcript of Introduction to JDBC - George Masonoffutt/classes/642/slides/642Lec08a-JDBC.pdf · Introduction to...

1

Introduction to JDBCIntroduction to JDBC

Michelle Lee Ye Wu & Jeff OffuttMichelle Lee, Ye Wu & Jeff Offutt

http://www.cs.gmu.edu/~offutt/

SWE 642Software Engineering for the World Wide Web

sources: Java for the Web with Servlets, JSP and EJB, Kurniawan, New RidersProfessional Java Server Programming, Patzer, Wrox

JDBCJDBC• JDBC API allows Java programs to connect to DBs

• Provides cross-vendor connectivity and data access yacross relational databases from different vendors

• Classes and interfaces allow users to access the database in a standard way

• The JVM uses the JDBC driver to translate generalized JDBC calls into vendor specific database calls

22-Oct-13 © Wu, Lee & Offutt 2

2

JDBC=Java Data Base Connectivity ?JDBC=Java Data Base Connectivity ?• Most people believe that JDBC stands for Java Data Base

Connectivity• But not quite—it used to be, but now is a trademarked q

name• Excerpt :

– “JDBC (TM) is a Java (TM) API for executing SQL statements. (As a point of interest, JDBC is a trademarked name and is not an acronym; nevertheless, JDBC is often thought of as standing for `Java D t b C ti it ’ ) ”

22-Oct-13 © Wu, Lee & Offutt 3

Database Connectivity’.) ”

JDBC DriversJDBC Drivers

1. JDBC-ODBC bridge

2. Part Java, Part Native Driver

3. Intermediate DAccess Server

22-Oct-13 © Wu, Lee & Offutt 4

4. Pure Java Drivers

3

1. JDBC1. JDBC--ODBC BridgeODBC Bridge• ODBC (Open DataBase Connectivity)

A set of APIs for database accessOriginally only for windows platforms, later extended to Originally only for windows platforms, later extended to non-windows platforms

• Originally C interfaces• Hard to learn• The standard JDK includes classes for the JDBC-ODBC

bridge (sun jdbc odbc JdbcOdbcDriver)bridge (sun.jdbc.odbc.JdbcOdbcDriver)

• There is no need for additional installation, apart from having to configure the ODBC driver by creating data source names

22-Oct-13 © Wu, Lee & Offutt 5

1. JDBC1. JDBC--ODBC Bridge (2)ODBC Bridge (2)

JavaClient

Server

ApplicationData Source

22-Oct-13 © Wu, Lee & Offutt 6

JDBC API

JDBC-ODBCBridge

ODBC API

ODBCLayer

4

2. Part Java, Part Native Driver2. Part Java, Part Native Driver• A mixture of Java implementation and vendor-specific

native APIs for data access

• This is similar to type 1 except that these have one less layer to go through and so is faster

• The native JDBC driver (part Java, part native code) must be installed on each client along with the vendor-specific

22-Oct-13 © Wu, Lee & Offutt 7

native language API

2. 2. Part JavaPart Java, , Part NPart Native ative DriverDriver (2)(2)

JClient

Server

JavaApplication

Data Source

22-Oct-13 © Wu, Lee & Offutt 8

JDBC API

JDBC Driver Vendor API

5

3. Intermediate Database Access 3. Intermediate Database Access ServerServer

• Based on intermediate (middleware) database servers

• Connect to various database servers via an intermediate server that acts like a gateway for multiple database servers

• The intermediate server can abstract details to

22-Oct-13 © Wu, Lee & Offutt 9

• The intermediate server can abstract details to connections to database servers

3. Intermediate Database Access 3. Intermediate Database Access ServerServer (2)(2)

Client

Server

JavaApplication

Client

Data Source

22-Oct-13 © Wu, Lee & Offutt 10

JDBCAPI

JDBC DriverNativeDriver

JDBC DriverServer

6

4. Pure Java Driver4. Pure Java Driver• Convert the JDBC API calls to direct network calls

– Using vendor-specific networking protocols– Making direct socket connections with the database

• It is the most efficient method to access database both in • It is the most efficient method to access database, both in performance and development time

• It is the simplest to deploy• All major database vendors provide Type 4 JDBC drivers

for their databases– Also available from third party vendors

• A list of JDBC drivers:• A list of JDBC drivers:– http://www.java2s.com/Tutorial/Java/0340__Database/AListofJD

BCDriversconnectionstringdrivername.htm

22-Oct-13 © Wu, Lee & Offutt 11

4. Pure Java Driver (2)4. Pure Java Driver (2)

JClient

Server

JavaApplication

Data Source

22-Oct-13 © Wu, Lee & Offutt 12

JDBC API

JDBC Driver

7

Typical JDBC Programming Typical JDBC Programming ProcedureProcedure

1 Load the database driver1. Load the database driver2. Obtain a connection3. Create and execute statements4. Use result sets to navigate through the results5 Close the connection

22-Oct-13 © Wu, Lee & Offutt 13

5. Close the connection

Driver ManagerDriver Manager• The purpose of the java.sql.DriverManger class in JDBC

is to provide a common access layer on top of different database drivers used in an application

• DriverManager requires that each driver required by the application must be registered before use

• Load the database driver using ClassLoader :

22-Oct-13 © Wu, Lee & Offutt 14

– Class.forName (“oracle.jdbc.driver.OracleDriver”);

8

Connecting to a DatabaseConnecting to a Database

• Type 4 JDBC Driver– Oracle ServerClass.forName ("oracle.jdbc.driver.OracleDriver");

D i M tC ti ( con = DriverManager.getConnection ( "jdbc:oracle:thin:@apollo.vse.gmu.edu:1521:ite10g",“your_username", “your_oracle_password");

– “your_username” is the same as your Mason ID– “your_oracle_password” is created when you activate

your Oracle account at https://access.vse.gmu.edu/

22-Oct-13 © Wu, Lee & Offutt 15

– MySQL ServerClass.forName ("org.gjt.mm.mysql.Driver");con = DriverManager.getConnection

("jdbc:mysql://localhost/databasename", uid, passwd);

Creating and Executing SQL Creating and Executing SQL StatementsStatements

• Statement object– Statement statement = con.createStatement();– statement.executeUpdate (“CREATE TABLE

STUDENT”);– statement.executeQuery (“SELECT * FROM

STUDENT”);

22-Oct-13 © Wu, Lee & Offutt 16

9

SQL StatementsSQL Statements• Create Tables

CREATE TABLE table (field type [(size)] [NOT NULL] [index1], …, [CONSTRAINT multifieldindex …)

• Create IndexCreate [UNIQUE] INDEX index ON table (field [ASC|DESC],….) [WITTH {PRIMARY|DISALLOW NULL|IGNORE NULL}]

22-Oct-13 © Wu, Lee & Offutt 17

• DropDrop TABLE tableDrop INDEX index ON table

SQL Statements (2)SQL Statements (2)• Alter Table

ALTER TABLE table {ADD {COLUMN field type…} |DROP {COLUMN field|CONSTRAINT indexname}}

• DELETEDELETE FROM table WHERE criteria

• InsertINSERT INTO target [(field1, …)] VALUES (value1,…)

• Update

22-Oct-13 © Wu, Lee & Offutt 18

UpdateUPDATE table SET newvalue WHERE criteria

10

SQL Statements (3)SQL Statements (3)• Select

SELECT {*|table.*|[table].field} FROM tableexpression WHERE {criteria| [NOT] [IN] (value1 )} [GROUP BY] [HAVING] [ORDER BY] (value1…)} [GROUP BY] [HAVING] [ORDER BY] ….

• Select intoSELECT fields INTO newtable FROM SOURCE

• Select subquery

22-Oct-13 © Wu, Lee & Offutt 19

Select subquerySELECT selectstatement(SELECT selectstatement (SELECT selectatement))

Creating Tables ExamplesCreating Tables Examples

• Creating a Coffee tableCREATE TABLE COFFEES (COF NAME CREA E ABLE COFFEES (COF_NAME

VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, SALES INTEGER, TOTAL INTEGER)

• Creating JDBC statementsStatement stmt = con.createStatement ();

• Execute a statement

SQL query

22-Oct-13 © Wu, Lee & Offutt 20

stmt.executeUpdate ("CREATE TABLE COFFEES " +"(COF_NAME VARCHAR(32), SUP_ID INTEGER,

PRICE FLOAT,” +"SALES INTEGER, TOTAL INTEGER)");

11

Checking to See if a Table Checking to See if a Table ExistsExists

Use meta data about the tableDatabaseMetaData dmd = con getMetaData();DatabaseMetaData dmd = con.getMetaData();ResultSet rs = dmd.getTables (null, null,

“COFFEES", null);if (rs == null) {

// table does not exist create it

22-Oct-13 © Wu, Lee & Offutt 21

// table does not exist, create it. }

Execute StatementsExecute Statements• This uses executeUpdate because the SQL statement

contained in createTableCoffees is a data definition language ( DDL ) statement

• DDL statements are executed with executeUpdate– Create a table– Alter a table– Drop a table

• executeUpdate is also used to execute SQL statements

22-Oct-13 © Wu, Lee & Offutt 22

pthat update a table

12

Execute StatementsExecute Statements• executeUpdate is used far more often to update tables

than to create them– We create a table once but update it many times

• The method used most often for executing SQL statements is executeQuery

• executeQuery is used to execute SELECT statements

22-Oct-13 © Wu, Lee & Offutt 23

y– SELECT statements are the most common SQL statements

Entering Data to a TableEntering Data to a Table

Statement stmt = con.createStatement(); stmt.executeUpdate ( "INSERT INTO COFFEES " +

"VALUES ('Colombian', 101, 7.99, 0, 0)"); stmt.executeUpdate ("INSERT INTO COFFEES " +

"VALUES ('French_Roast', 49, 8.99, 0, 0)"); stmt.executeUpdate ("INSERT INTO COFFEES " +

"VALUES ('Espresso', 150, 9.99, 0, 0)"); stmt.executeUpdate ("INSERT INTO COFFEES " +

"VALUES ('Colombian Decaf' 101 8 99 0 0)");

22-Oct-13 © Wu, Lee & Offutt 24

VALUES ( Colombian_Decaf , 101, 8.99, 0, 0) ); stmt.executeUpdate ("INSERT INTO COFFEES " +

"VALUES ('French_Roast_Decaf', 49, 9.99, 0, 0)");

13

Prepared StatementPrepared Statement• A PreparedStatement object can hold precompiled SQL

statements• If the same SQL statement is executed many times with Q y

different parameters, it is more efficient to use a PreparedStatement object

• Examples:PreparedStatement pstat = connection.prepareStatement

(“Insert into” student (title, ...) values (?, ?, ..) );

22-Oct-13 © Wu, Lee & Offutt 25

pstat.setString (1, name);pstat.executeUpdate();

Getting and Using Data From Getting and Using Data From TablesTables

ResultSet rs = stmt.executeQuery ("SELECT COF_NAME, PRICE FROM COFFEES");

while (rs next()) while (rs.next()) {

String s = rs.getString ("COF_NAME"); float n = rs.getFloat ("PRICE"); System.out.println (s + " " + n);

}

22-Oct-13 © Wu, Lee & Offutt 26

}

14

Navigating Result SetsNavigating Result SetsJDBC Types Mapped to Java Types

JDBC Types Java Types JDBC Types Java Types

CHAR String DATE Java.sql.Date

VARCHAR St i TIME J l TiVARCHAR String TIME Java.sql.Time

LONGVARCHAR String TIMESTAMP Java.sql.Timestamp

TINYINT short

INTEGER Int JAVAOBJECT Object

BIGINT Long BLOB Java.sql.Blobinterface

REAL Float CLOB Java.sql.Clob

22-Oct-13 © Wu, Lee & Offutt 27

qinterface

FLOAT Double ARRAY Java.sql.Arrayinterface

DOUBLE Double STRUCT

BIT boolean REF

Navigating Result SetsNavigating Result SetsResultSetResultSet rs = statement.exeuteQuery (“select * from student”);while (rs.netxt()){

System.out.print (rs.getString (“name”) + …}

ResultSetMetaData metaData = rs.getMetaData();t D t tC l C t()

22-Oct-13 © Wu, Lee & Offutt 28

metaData.getColumnCount();metaData.getColumnName (I);metaData.getColumnType (I);

15

Navigating Result SetsNavigating Result Sets• A default ResultSet object is read-only (not updateable) and has a

cursor that moves forward only ( next() ).

S • Scrollable result sets have more operationsFirst, last, absolute, relative, next, previous, beforeFirst, afterLast, isFirst isBeforeFirst, isLast, isAfterLast

22-Oct-13 © Wu, Lee & Offutt 29

Batch UpdateBatch Update• What is batch update?

– Send multiple update statement in a single request to the database

• Why batch update?– Better performance

• How do we perform batch update?– Statement.addBatch (sqlString);

St t t t B t h()

22-Oct-13 © Wu, Lee & Offutt 30

– Statement.executeBatch();

16

Transaction SupportTransaction Support• A database transaction is a work unit treated in a

coherent and reliable way independent of other transactions

• If a transaction starts, all pieces must complete• Two main purposes :

– Allow recovery from errors when operations do not complete– Provide concurrency control

• A database transaction must be ACID :

22-Oct-13 © Wu, Lee & Offutt 31

– Atomic– Consistent– Isolated– Durable

Transaction Support (2)Transaction Support (2)• By default, a connection is in auto-commit mode

– Each individual SQL statement is treated as a transaction

• To turn off auto-commit mode :– connection.setAutoCommit (false);

• Commit and Rollback– Commit – a call to commit() will commit everything that was

done since the last commit was issued– Rollback – a call to rollback() will undo any changes since the

22-Oct-13 © Wu, Lee & Offutt 32

last commit

17

Exception HandlingException Handling• Objectives

– Handle exceptions gracefully– Maintain the integrity of the database

• Exception handling with a rollback :try {

con.setAutoCommit (false);statement.executeUpdate (“….”);statement.executeUpdate (“….”);commit(); con.setAutoCommit (true);

}catch (SQLException ex){ con rollback(); }

22-Oct-13 © Wu, Lee & Offutt 33

{ con.rollback(); }• SQL warnings

ResultSet rs = statement.executeQuery (“Select * from student”);SQLWarning warn = statement.getWarnings();if (warn != null)

System.out.println (warn.getMessage());

JDBC SummaryJDBC Summary• Most web applications use databases to store data in a

persistent way

• The techniques for accessing databases from Java programs are identical in web applications and in stand-alone Java programs

• This lecture does not teach how to set up or use a database or the details of constructing SQL queries– INFS 614, Database Management– INFS 740, Database Programming for the World Wide Web

22-Oct-13 © Wu, Lee & Offutt 34