JDBC

49
IT G ROUP JDBC Olivier de Pertat

description

JDBC. Olivier de Pertat. JDBC Overview. JDBC is specified as an Interface API to manage and query RDBMS New standard to access RDMS : single API to access envry single product JDBC Allows to : Run SQL Queries (Static or dynamic, DML or DDL instructions) Process the results - PowerPoint PPT Presentation

Transcript of JDBC

Page 1: JDBC

IT GROUP

JDBC

Olivier de Pertat

Page 2: JDBC

JDBC Overview

JDBC is specified as an InterfaceAPI to manage and query RDBMSNew standard to access RDMS : single API to access envry single productJDBC Allows to :

Run SQL Queries (Static or dynamic, DML or DDL instructions)Process the results

Specification based on the X/Open SQL CLI standard (like ODBCAlternative to proprietary solutions (Oracle, Sybase, DB2…)

Page 3: JDBC

Simplified DBMS Architecture

Page 4: JDBC

DBMS Goals

Efficient data Management (faster than files)

Larger amout of data

High reliability

Information sharing (multiple users)

DBMS Users :Banks, Insurances, airlines, E-commerce companies, transportation companies, corporate DB, government agencies…

Everybody nowadays!

Page 5: JDBC

DBMS Concepts

Database modelingE/R model, Relational model, ER to Relational Model

Relational Algebra

SQL: Subqueries, Joins, Modifications, NULLs, Constraints, Triggers, stored procedures

Embedded SQL

Views

Relational Design: BCNF, 2NF, 3NF, 4NF, 5NF…

Page 6: JDBC

JDBC & SQL

SQL-3 Entry Level SupportDynamic SQL, most SQL types

Transactions, basic cursors

Meta-data (Database Dictionary access)

Extension mechanismSyntax inspired from ODBC: { keywords... parameters ... }

ODBC conversions functions, mathematics, etc.

Long terme:Support de SQL-3 complet

Page 7: JDBC

JDBC Versions

JDBC 1.0 : Integrated to Java 1.1

JDBC 2.0 API : JDBC 2.1 Core API : since J2SE 1.2 (java.sql)

JDBC 2.0 Optional Package : since J2EE 1.2 (javax.sql)

JDBC 3.0 :JDBC 3.0 Core API : since J2SE 1.4

JDBC 3.0 Optional Package :

Page 8: JDBC

New in JDBC 2.0

JDBC 2.1 Core APIScrollable ResultSets

Update through ResultSets is possible

Minimal support of BLOB & CLOB data types

User-defined types support

Bacth updates.

JDBC 2.0 Optional PackageDataSource

Distributed Transactions (JTA/XA)

Connection Pools

RowSet Technology

.

Page 9: JDBC

JDBC 3.0 Newbie

Statements Pools

SavePoints in transaction

MetaData for PreparedStatements

Enhancement of CallableStatements (types of parameters, multiple ResultSet... )

Management of object types : BLOB, CLOB, ARRAY et REF.

Page 10: JDBC

J2EE integration - 1

Page 11: JDBC

J2EE Integration - 2

Page 12: JDBC

Drivers Topology

JDBC interacts with the RDMS through a DriverManager

Drivers are available for most commercial & OpenSource Databases :Oracle, DB2, Sybase, MySQL, PostgreSQL, ODBC...

4 drivers topology:1. Bridge ODBC (given with JDBC)2. Native-API partly-Java driver3. JDBC-Net all-Java driver4. Native-protocol all-Java driver

1. et 2 are written with Native code..

Page 13: JDBC

JDBC Type 1 : JDBC-ODBC Brigde

Page 14: JDBC

JDBC Type 2: Native-API Partly-Java Driver

Page 15: JDBC

JDBC Type 3 : Net Protocol All-Java Driver

Page 16: JDBC

JDBC Type 4 : All Java Driver

Page 17: JDBC

JDBC : Architecture Objet

Page 18: JDBC

JDBC Components

Driver Manager: loads database drivers and manages the connection between application & driver.

Driver: translates API class to operations for a specific data source.

Connection: A session between an application and a driver.

Statement: A SQL statement to perform a query or an update operation.

Metadata: Information about the returned data, driver and the database.

ResultSet : logical set of columns and rows returned by executing a statement.

Page 19: JDBC

Java.sql

JDBC is implemented via classes in the java.sql package

Defines object for:Remote connection to DBExecuting query

8 interfaces to define objectsStatement, CallableStatement, PreparedStatement, DatabaseMetaData, ResultSetMetaData, Connection, Driver

Page 20: JDBC

JDBC Classes

Java supports DB facilities b y providing classes and interfaces for its components.

DriverManager : class

Connection : Abstract Class

Statement : Interface (to be instantiated with values from the actual SQL Statement)

ResulSet : Interface

Page 21: JDBC

Seven steps to heaven (or a DBMS ;-))

Load the Driver

Define the Connection URL

Establish the Connection

Create a Statement object

Execute a query

Process the result

Close the connection

Page 22: JDBC

Loading the driver v1

Registering the driver directly Use the method forName from the class: Class

Creates an instance of the Driver

Registers the Driver with the DriverManager

Class.forName("sun.jdbc.odbc.JdbcOrdbDriver");

Class.forName("oracle.jdbc.driver.OracleDriver");

Example :Try

{

Class.forName(« oracle.jdbc.driver.OracleDriver ») ;

}

catch(ClassNotFoundException e)

{

e.printStackTrace(); ;

}

Page 23: JDBC

Loading the driver v2

Anther option is to creates an instance of the driver then manually register it :Driver driver = new oracle.jdbc.driver.OracleDriver();

DriverManager.registerDriver(driver);

Page 24: JDBC

Identifying the Data Source

Gives the required information for making the connection to the databases

URL :<scheme>:<sub scheme>:<scheme-specific part>

Scheme : Protocol => JDBC

Sub Scheme : indicates driver & driver type

Scheme Specific part : Server Address & Database name

Examples : jdbc:odbc:my_database

jdbc:oracle:thin:@localhost:1521:ODP

Page 25: JDBC

Connection

A connection represents a session with a specific database

Within the context of a connection SQL statements are executed and results returned (or an Integer if Query is not a SELECT statement)

There can be multiple connections to a database

A connection provides ”metadata” i.e., information about the database, tables, fields.

Connection object has methods to deal with the transactions.

Connection creation : Connection conn = DriverManager.getConnection(url, user, password);.

Page 26: JDBC

Connection Metadata

getMetaData() method returns a JDBC Metadata connection

Returned type if DatabaseSetMetaData.

Information returned by this object:What tables are available?

What's our user name as known to the database?

Is the database in read-only mode?

If table correlation names are supported (association of a column with the table it comes from, when multiple columns of the same name appear in the same query - multi-table queries) , are they restricted to be different from the names of the tables?

and so on…

Page 27: JDBC

Statements

A statement object is used for executing a static SQL statement and obtaining the results produced by it.

3 kinds of statements:statement :

for general queries<Connection>.createStatement() method

prepared statement : For a statement called multiple times with different values (precompiled to reduce parsing time)<Connection>.preparedStatement() method

callable statementfor stored procedures<Connection>.preparedCall() method

Sample:Statement stmt = conn.createStatement();

Page 28: JDBC

Executing Queries and updates

ResultSet executeQuery(String)Execute a SQL statement that returns a single ResultSet

int executeUpdate(String)Execute a SQL INSERT, UPDATE or DELETE statement

Used for CREATE TABLE, DROP TABLE and ALTER TABLE

Returns the number of rows changed

setQueryTimeOutto set a timeout for the driver to wait for a statement to be completed

If the operation is not compeleted in the given time, an SQLException is thrown

Page 29: JDBC

Executing a request

Execution of a request:

String myQuery = "SELECT prenom, nom, email " +

"FROM employe " +

"WHERE (nom='Dupont') AND (email IS NOT NULL"+

"ORDER BY nom";

ResultSet rs = stmt.executeQuery(myQuery);

Page 30: JDBC

Result Set - 1

A Result Set provides access to a table of data generated by executing a Statement.Only one ResultSet per Statement can open at once.The table rows are retrieved in sequence.A ResultSet maintains a cursor pointing to its current row of data.The next method moves the cursor forward (to the next row).Columns are indexed by name or number.

.

Page 31: JDBC

Result Set - 2

Data is retrieved from a column via the getXXX methods where XXX is the type of the returned Java object.The content Cells containing a “large amount” of data must be retrieved via streams.Type getType(int columnIndex)

returns the given field as the given typeE.g., int getInt(5); string getString(3);fields indexed starting at 1 (not 0)

Type getType(String columnName)same, but uses name of fieldless efficient

int findColumn(String columnName)looks up column index given column name

Page 32: JDBC

Result Set – 3 – isNull

In SQL, NULL means the field is empty

Not the same as 0 or “”

In JDBC, you must explicitly ask if a field is null by calling ResultSet.isNull(column)

Page 33: JDBC

Example

java.sql.Statement stmt = conn.createStatement();

ResultSet rs =

stmt.executeQuery("SELECT a, b, c FROM Table1");

while (rs.next())

{

// print the values for the current row.

int i = rs.getInt("a");

String s = rs.getString("b");

byte b[] = rs.getBytes("c");

System.out.println("ROW = " + i + " " + s + " " + b[0]);

}

Page 34: JDBC

ResultSet’s metadata

getMetaData() method returns a ResultSetMetaData object.

Information:What's the number of columns in the ResultSet?

What's a column's name?

What's a column's SQL type?

What's the column's normal max width in chars?

What's the suggested column title for use in printouts and displays?

What's a column's number of decimal digits?

Does a column's case matter?

and so on...

Page 35: JDBC

Full example

public class TestJDBC {

public static void main(String[] args) throws Exception {

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection conn =

DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:ODP", "user", "");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * from employe");

while (rs.next()) {

String nom = rs.getString("nom");

String prenom = rs.getString("prenom");

String email = rs.getString("email");

}

}

}

Page 36: JDBC

Mapping Java types to SQL Types

SQL type Java TypeCHAR, VARCHAR, LONGVARCHAR StringNUMERIC, DECIMAL java.math.BigDecimalBIT booleanTINYINT byteSMALLINT shortINTEGER intBIGINT longREAL floatFLOAT, DOUBLE doubleBINARY, VARBINARY, LONGVARBINARY byte[]DATE java.sql.DateTIME java.sql.TimeTIMESTAMP java.sql.Timestamp

Page 37: JDBC

Types Oracle – JDBC 1.0

Page 38: JDBC

Types Oracle – JDBC 2.0

Page 39: JDBC

Database time

Times in SQL are nonstandard

Java defines three classes to help

java.sql.Dateyear, month, day

java.sql.Timehours, minutes, seconds

java.sql.Timestampyear, month, day, hours, minutes, seconds, nanoseconds

usually use this one

Page 40: JDBC

Optimized Statements

Prepared StatementsSQL calls that you make again and again

allows driver to optimize (compile) queries

created with Connection.prepareStatement()

Stored Procedureswritten in DB-specific language

stored inside database

accessed with Connection.prepareCall()

Page 41: JDBC

Prepared Statement example

PreparedStatement pstmt =

con.prepareStatement("UPDATE PEOPLE SET PHOTO_FILENAME=?,PHOTO_DATA=? WHERE

ID=?",

ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);

pstmt.setString(1, myFile.getName());

pstmt.setBinaryStream(2, myFileInput,

myFileInput.available());

pstmt.setString(3, "27");

pstmt.execute();

pstmt.close();

Page 42: JDBC

JDBC Class Diagram

Page 43: JDBC

Transaction management

A transaction: a sequence of SQL statements betwwen

BEGIN_TRANSACTION : débutEt COMMIT_TRANSACTION ou ROLLBACK_TRANSACTION

Transactions are not explicitly opened and closedInstead, the connection has a state called AutoCommit modeif AutoCommit is true, then every statement is automatically committeddefault case: trueExample : CompteA += 100CompteB -= 100

Page 44: JDBC

Auto commit

Connection.setAutoCommit(boolean)

if AutoCommit is false, then every statement is added to an ongoing transaction

you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback()

Page 45: JDBC

Transactions isolation levels

TRANSACTION_NONENo transaction support

TRANSACTION_READ_UNCOMMITEDminimal supportDirty read i.e. no warranty

TRANSACTION_READ_COMMITEDDirty read impossible

TRANSACTION_REPEATABLE_READRepeatable read protectedAnd TRANSACTION_READ_COMMITED support.

TRANSACTION_SERIALIZABLEInsertion protectectionAnd TRANSACTION_REPEATABLE_READ support.

Page 46: JDBC

Example

Transaction mode activated via setAutoCommit method of Connection.Example : setTransactionIsolation.

Try {

con.setAutoCommit(false); con.setTransactionIsolation( Connection.TRANSACTION_READ_COMMITED); //SQL stuff con.commit();}Catch(Exception e) { con.rollback();}

.

Page 47: JDBC

Transactional modes

Transactional support is database specific material.DB2 UDB : all levelsOracle : 2 levels supportedMySQL : only one level is supported

Transaction information relatives are specified in the class DatabaseMetaData:

supportsTransactions()supportsDataDefinitionAndDataManipulationTransactions()getDefaultTransactionIsolation()dataDefinitionCausesTransactionCommit()supportsTransactionIsolationLevel(int)

o

Page 48: JDBC

Connection Manager

For a large threaded database server, create a Connection Manager objectIt is responsible for maintaining a certain number of open connections to the databaseWhen your applications need a connection, they ask for one from the CM’s poolWhy? Because opening and closing connections takes a long timeWarning: the CM should always setAutoCommit(false) when a connection is returned

.

Page 49: JDBC

Thanks to…

O’reilly Editions

Eyrolles editions

A. Chambrey (BD2 - Eyrolles)

Professor Chen Li – University of California, Irvine