Prepared by ViskaMutiawaniinformatika.unsyiah.ac.id/~viska/pjl/P2-2 JDBC.pdfType 1: JDBC-ODBC Bridge...

Post on 19-Dec-2020

3 views 0 download

Transcript of Prepared by ViskaMutiawaniinformatika.unsyiah.ac.id/~viska/pjl/P2-2 JDBC.pdfType 1: JDBC-ODBC Bridge...

JDBC

Prepared by Viska Mutiawani

1 viska@unsyiah.ac.id

Subtopik JDBC

Pengenalan JDBC

JDBC driver

Package java.sql

Cara menggunakan JDBC

Advance

2 viska@unsyiah.ac.id

Pengenalan JDBC

3 viska@unsyiah.ac.id

JDBC – Java Database Connectivity

JDBC is a standard interface for connecting to relational databases from Java.

The JDBC classes and interfaces are in the java.sqlpackage.

JDBC 1.22 is part of JDK 1.1; JDBC 2.0 is part of Java 2

4 viska@unsyiah.ac.id

Apakah itu JDBC?

JDBC provides Java applications with access to most database systems via SQL

The architecture and API closely resemble Microsoft's ODBC

JDBC 1.0 was originally introduced into Java 1.1

JDBC 2.0 was added to Java 1.2

JDBC is based on SQL-92

JDBC classes are contained within the java.sql package

There are few classes

There are several interfaces

5 viska@unsyiah.ac.id

Database connectivity history

Before APIs like JDBC and ODBC, database connectivity was tedious

Each database vendor provided a function library for accessing their database

The connectivity library was proprietary.

If the database vendor changed for the application, the data access portions had to be rewritten

If the application was poorly structured, rewriting its data access might involve rewriting the majority of the application

The costs incurred generally meant that application developers were stuck with a particular database product for a given application

6 viska@unsyiah.ac.id

Arsitektur JDBC

With JDBC, the application programmer uses the JDBC API

The developer never uses any proprietary APIs

• Any proprietary APIs are implemented by a JDBC driver

• There are 4 types of JDBC Drivers

Java Application

JDBC API

JDBC DriverManager

JDBC Driver JDBC Driver

7 viska@unsyiah.ac.id

JDBC Drivers

8 viska@unsyiah.ac.id

JDBC Drivers

There are 4 types of JDBC Drivers: Type 1 - JDBC-ODBC Bridge

Type 2 - JDBC-Native Bridge

Type 3 - JDBC-Net Bridge

Type 4 - Direct JDBC Driver

Type 1 only runs on platforms where ODBC is available ODBC must be configured separately

Type 2 Drivers map between a proprietary Database API and the JDBC API

Type 3 Drivers are used with middleware products

Type 4 Drivers are written in Java

In most cases, type 4 drivers are preferred

9 viska@unsyiah.ac.id

JDBC Driver Types

10 viska@unsyiah.ac.id

Type 1: JDBC-ODBC Bridge Driver

This is an approach wherein the implemented class in Java makes calls to the code written in Microsoft languages (native), which speaks directly to the database.

The first category of JDBC drivers provides a bridge between the JDBC and the ODBC API . The bridge translates the standard JDBC calls and sends them to the ODBC data source via ODBC libraries .

Type 1 drivers use a bridge technology to connect a Java client to an ODBC database system. The JDBC-ODBC Bridge from Sun and InterSolv is the only extant example of a Type 1 driver. Type 1 drivers require some sort of non-Java software to be installed on the machine running your code, and they are implemented using native code.

11 viska@unsyiah.ac.id

Type 2: JDBC-Native API In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls

which are unique to the database. These drivers typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine.

This is an approach wherein the implemented class in Java makes calls to the code written from the database provider (native), which speaks directly to the database.

If we change the Database we have to change the native API as it is specific to a database and they are mostly obsolete now but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's overhead.

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

12 viska@unsyiah.ac.id

Type 3: JDBC-Net pure Java In a Type 3 driver, a three-tier approach is used to accessing databases. The

JDBC clients use standard network sockets to communicate with an middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.

You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client application. As a result, you need some knowledge of the application server's configuration in order to effectively use this driver type.

The Java client application sends a JDBC calls through a JDBC driver to the intermediate data access server ,which completes the request to the data source using another driver . This driver uses a database independent protocol , to communicate database request to a server component which then translate the request into a DB specific protocol .

13 viska@unsyiah.ac.id

Type 4: 100% pure Java In a Type 4 driver, a pure Java-based driver that communicates directly with

vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself.

This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

This is an approach wherein the implemented class in Java (implemented by the database provider) speaks directly to the database. In other words , it is a pure Java library that translates JDBC request directly to a Database specific protocol .

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers.

14 viska@unsyiah.ac.id

So which driver?

If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.

If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver.

Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your database.

The type 1 driver is not considered a deployment-level driver and is typically used for development and testing purposes only.

15 viska@unsyiah.ac.id

Package java.sql

16 viska@unsyiah.ac.id

JDBC Components

17 viska@unsyiah.ac.id

JDBC Classes

DriverManager

Manages JDBC Drivers

Used to Obtain a connection to a Database

Types

Defines constants which identify SQL types

Date

Used to Map between java.util.Date and the SQL DATE type

Time

Used to Map between java.util.Date and the SQL TIME type

TimeStamp

Used to Map between java.util.Date and the SQL TIMESTAMP type

18 viska@unsyiah.ac.id

JDBC Interfaces

Driver

All JDBC Drivers must implement the Driver interface. Used to obtain a connection to a specific database type

Connection

Represents a connection to a specific database

Used for creating statements

Used for managing database transactions

Used for accessing stored procedures

Used for creating callable statements

Statement

Used for executing SQL statements against the database

19 viska@unsyiah.ac.id

JDBC Interfaces ResultSet

Represents the result of an SQL statement Provides methods for navigating through the resulting data

PreparedStatement Similar to a stored procedure An SQL statement (which can contain parameters) is compiled

and stored in the database

CallableStatement Used for executing stored procedures

DatabaseMetaData Provides access to a database's system catalogue

ResultSetMetaData Provides information about the data contained within a

ResultSet

20 viska@unsyiah.ac.id

Cara Menggunakan JDBC

21 viska@unsyiah.ac.id

Using JDBC To execute a statement against a database, the following flow is

observed Load the driver (Only performed once) Obtain a Connection to the database (Save for later use) Obtain a Statement object from the Connection Use the Statement object to execute SQL. Updates, inserts and deletes

return Boolean. Selects return a ResultSet Navigate ResultSet, using data as required Close ResultSet Close Statement

Do NOT close the connection The same connection object can be used to create further statements A Connection may only have one active Statement at a time. Do not

forget to close the statement when it is no longer needed. Close the connection when you no longer need to access the database

22 viska@unsyiah.ac.id

Query

Close

Connect

Processresults

Overview of Querying a Database With JDBC

23 viska@unsyiah.ac.id

Query

Close

Connect

Processresults

Register the driver

Connect to the database

Stage 1: Connect

24 viska@unsyiah.ac.id

Is an interpreter that translates JDBC method calls to vendor-specific database commands

Implements interfaces in java.sql

Can also provide a vendor’s extensions to the JDBC standard

DriverJDBC calls

Database commands

Database

A JDBC Driver

25 viska@unsyiah.ac.id

About JDBC URLs

JDBC uses a URL to identify the database connection.

jdbc:<subprotocol>:<subname>

ProtocolDatabaseidentifier

jdbc:oracle:<driver>:@<database>

Subprotocol

26 viska@unsyiah.ac.id

Nama URL database:

JDBC-ODBC :

jdbc:odbc:nama_database

Oracle :

jdbc:oracle:thin:@nama_host:1521:namaDB

MySQL:

jdbc:mysql://nama_host:3306/namaDB

PostgreSQL:

jdbc:postgresql://nama_host:5432/namaDB

Microsoft SQLServer 2000 :

jdbc:microsoft:sqlserver://nama_host:1433;DatabaseName=namaDB

27 viska@unsyiah.ac.id

Thin driver

OCI driver

Server-side driver: Use the default connection

jdbc:oracle:thin:@<host>:<port>:<SID>

jdbc:oracle:oci8:@<TNSNAMES entry>

JDBC URLs with Oracle Drivers

28 viska@unsyiah.ac.id

Class.forName("com.mysql.jdbc.Driver");

Connection conn = DriverManager.getConnection

(URL, userid, password);

Connection Connection connconn = =

DriverManager.getConnectionDriverManager.getConnection("("jdbc:mysqljdbc:mysql://://locloc

alhostalhost/books", "root", "/books", "root", "mysqlmysql");");

2. Connect to the database.

How to Make the Connection

1. Register the driver.

29 viska@unsyiah.ac.id

Using Connection

java.sql.Connection Creating Statement

Transaction Management

Get database metadata

Connection related

createStatement()prepareStatement(String)

prepareCall(String)

commit()rollback()

getMetaData()

close()isClosed()

30 viska@unsyiah.ac.id

Close

Connect

Query Create a statement

Processresults

Query the database

Stage 2: Query

31 viska@unsyiah.ac.id

The Statement Object

A Statement object sends your SQL statement to the database.

You need an active connection to create a JDBC statement.

Statement has three methods to execute a SQL statement: executeQuery() for QUERY statements executeUpdate() for INSERT, UPDATE, DELETE, or

DDL statements execute() for either type of statement

32 viska@unsyiah.ac.id

1. Create an empty statement object.

2. Execute the statement.

Statement stmt = conn.createStatement();

ResultSet rset = stmt.executeQuery(statement);

int count = stmt.executeUpdate(statement);

boolean isquery = stmt.execute(statement);

How to Query the Database

33 viska@unsyiah.ac.id

Statement stmt = conn.createStatement();

ResultSet rset = stmt.executeQuery

("select RENTAL_ID, STATUS from ACME_RENTALS");

Statement stmt = conn.createStatement();

int rowcount = stmt.executeUpdate

("delete from ACME_RENTAL_ITEMS

where rental_id = 1011");

Querying the Database: Examples

Execute a select statement.

• Execute a delete statement.

34 viska@unsyiah.ac.id

Close

QueryStep through the results

Processresults

Assign results to Java variables

Connect

Stage 3: Process the Results

35 viska@unsyiah.ac.id

The ResultSet Object

JDBC returns the results of a query in a ResultSet object.

A ResultSet maintains a cursor pointing to its current row of data.

Use next() to step through the result set row by row.

getString(), getInt(), and so on assign each value to a Java variable.

36 viska@unsyiah.ac.id

while (rset.next()) { … }

String val =

rset.getString(colname);

while (rset.next()) {

String title = rset.getString("TITLE");

String year = rset.getString("YEAR");

… // Process or display the data

}

String val =

rset.getString(colIndex);

How to Process the Results

1. Step through the result set.

2. Use getXXX() to get each column value.

37 viska@unsyiah.ac.id

while (rset.next()) {String year = rset.getString("YEAR");if (rset.wasNull() {

… // Handle null value}

…}

How to Handle SQL Null Values

Java primitive types cannot have null values.

Do not use a primitive type when your query might return a SQL null.

Use ResultSet.wasNull() to determine whether a column has a null value.

38 viska@unsyiah.ac.id

Mapping Database Types to Java Types

ResultSet maps database types to Java types.

ResultSet rset = stmt.executeQuery("select RENTAL_ID, RENTAL_DATE, STATUS from ACME_RENTALS");

int id = rset.getInt(1);Date rentaldate = rset.getDate(2); String status = rset.getString(3);

Col Name

RENTAL_ID

RENTAL_DATE

STATUS

Type

NUMBER

DATE

VARCHAR239 viska@unsyiah.ac.id

SQL Types/Java Types MappingSQL Type Java Type

CHAR String

VARCHAR String

LONGVARCHAR String

NUMERIC java.Math.BigDecimal

DECIMAL java.Math.BigDecimal

BIT boolean

TINYINT int

SMALLINT int

INTEGER int

BIGINT long

REAL float

FLOAT double

DOUBLE double

BINARY byte[]

VARBINARY byte[]

DATE java.sql.Date

TIME java.sql.Time

TIMESTAMP java.sql.Timestamp40 viska@unsyiah.ac.id

Connect

Query

Processresults

Close

Close the result set

Close the statement

Close the connection

Stage 4: Close

41 viska@unsyiah.ac.id

1. Close the ResultSet object.

2. Close the Statement object.

3. Close the connection (not necessary for server-side driver).

rset.close();

stmt.close();

conn.close();

How to Close the Connection

42 viska@unsyiah.ac.id

Connection aConnection;

try

{

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

}

catch(ClassNotFoundException x)

{

System.out.println("Cannot find driver class. Check CLASSPATH");

return;

}

try

{

aConnection = DriverManager.getConnection("jdbc:odbc:MyDatabase",

"Username", "Password");

}

catch(SQLException x)

{

System.out.println("Exception connecting to database:" + x);

return;

}

Example Code:

43 viska@unsyiah.ac.id

try

{

Statement aStmt = aConnection.createStatement();

StringBuffer sb = new StringBuffer("SELECT Employee_id, Employee_Name");

sb.append(" FROM Employee WHERE EmployeeId>100");

ResultSet rs = aStmt.executeQuery(sb.toString());

while(rs.next())

{

int employeeId = rs.getInt(1);

String employeeName = rs.getString(2);

System.out.println("Id:" + employeeId + "\nName:" + employeeName);

}

rs.close();

aStmt.close();

}

catch(SQLException x)

{

System.out.println("Exception while executing query:" + x);

}

Example Code (continued):

44 viska@unsyiah.ac.id

More AdvancedDynamic Query using MetaData

45 viska@unsyiah.ac.id

The DatabaseMetaData Object

The Connection object can be used to get a DatabaseMetaData object.

This object provides more than 100 methods to obtain information about the database.

46 viska@unsyiah.ac.id

1. Get the DatabaseMetaData object.

2. Use the object’s methods to get the metadata.

DatabaseMetaData dbmd = conn.getMetaData();String s1 = dbmd getURL();String s2 = dbmd.getSQLKeywords();boolean b1 = dbmd.supportsTransactions();boolean b2 = dbmd.supportsSelectForUpdate();

How to Obtain Database Metadata

DatabaseMetaData dbmd = conn.getMetaData();

47 viska@unsyiah.ac.id

The ResultSetMetaData Object

The ResultSet object can be used to get a ResultSetMetaData object.

ResultSetMetaData object provides metadata, including:

Number of columns in the result set

Column type

Column name

48 viska@unsyiah.ac.id

How to Obtain Result Set Metadata

1. Get the ResultSetMetaData object.

2. Use the object’s methods to get the metadata.

ResultSetMetaData rsmd = rset.getMetaData();for (int i = 0; i < rsmd.getColumnCount(); i++) {String colname = rsmd.getColumnName(i);int coltype = rsmd.getColumnType(i);…

}

ResultSetMetaData rsmd = rset.getMetaData();

49 viska@unsyiah.ac.id

The PreparedStatement Object

A PreparedStatement object holds precompiled SQL statements.

Use this object for statements you want to execute more than once.

A prepared statement can contain variables that you supply each time you execute the statement.

50 viska@unsyiah.ac.id

How to Create a Prepared Statement

1.Register the driver and create the database connection.

2.Create the prepared statement, identifying variables with a question mark (?).

PreparedStatement pstmt =conn.prepareStatement("update ACME_RENTALS

set STATUS = ? where RENTAL_ID = ?");

PreparedStatement pstmt =conn.prepareStatement("select STATUS from

ACME_RENTALS where RENTAL_ID = ?");

51 viska@unsyiah.ac.id

How to Execute a Prepared Statement

1. Supply values for the variables.

2. Execute the statement.

pstmt.setXXX(index, value);

pstmt.executeQuery();

pstmt.executeUpdate();

PreparedStatement pstmt =conn.prepareStatement("update ACME_RENTALSset STATUS = ? where RENTAL_ID = ?");

pstmt.setString(1, "OUT");pstmt.setInt(2, rentalid);pstmt.executeUpdate();

52 viska@unsyiah.ac.id

The CallableStatement Object

A CallableStatement object holds parameters for calling stored procedures.

A callable statement can contain variables that you supply each time you execute the call.

When the stored procedure returns, computed values (if any) are retrieved through the CallabableStatement object.

53 viska@unsyiah.ac.id

Register the driver and create the database connection.

Create the callable statement, identifying variables with a question mark (?).

CallableStatement cstmt = conn.prepareCall("{call " +ADDITEM + "(?,?,?)}");cstmt.registerOutParameter(2,Types.INTEGER);cStmt.registerOutParameter(3,Types.DOUBLE);

How to Create a Callable Statement

54 viska@unsyiah.ac.id

1. Set the input parameters.

2. Execute the statement.

3. Get the output parameters.

How to Execute a Callable Statement

cstmt.setXXX(index, value);

cstmt.execute(statement);

var = cstmt.getXXX(index);

55 viska@unsyiah.ac.id

Using Transactions

The server-side driver does not support autocommit mode.

With other drivers: New connections are in autocommit mode. Use conn.setAutoCommit(false) to turn autocommit

off.

To control transactions when you are not in autocommit mode: conn.commit(): Commit a transaction conn.rollback(): Roll back a transaction

56 viska@unsyiah.ac.id

57 viska@unsyiah.ac.id