0% found this document useful (0 votes)
197 views

JDBC - Java Database Connectivity

JDBC provides a standard API for connecting to and querying databases. There are 4 types of JDBC drivers: Type 1 uses ODBC, Type 2 uses native database APIs, Type 3 uses a network protocol and middle tier, and Type 4 uses a native network protocol. Type 4 drivers are considered best as they are fully Java and don't require additional software. The basic steps to query a database using JDBC are to connect, create a statement, execute a query, process the results, and close the connection.

Uploaded by

Raj Pal
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
197 views

JDBC - Java Database Connectivity

JDBC provides a standard API for connecting to and querying databases. There are 4 types of JDBC drivers: Type 1 uses ODBC, Type 2 uses native database APIs, Type 3 uses a network protocol and middle tier, and Type 4 uses a native network protocol. Type 4 drivers are considered best as they are fully Java and don't require additional software. The basic steps to query a database using JDBC are to connect, create a statement, execute a query, process the results, and close the connection.

Uploaded by

Raj Pal
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 38

JDBC Java Database Connectivity

It is an API which enables Java applications to connect and access databases

JDBC Architecture

JDBC API

available in java.sql and javax.sql packages

JDBC Drivers

classes available from different vendors which must be registered with JDBC DriverManager to connect to different databases

Steps of Querying a Database


Connect

Query

Process results

Close

Stage 1: Connect
Connect
Register the driver

Query

Connect to the database

Process results

Close

How to Make the Connection


1. Register the driver.
Class.forName(oracle.jdbc.driver.OracleDriver);

2. Connect to the database.


Connection conn = DriverManager.getConnection (URL, userid, password);

Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@myhost:1521:orcl", "scott", "tiger");

About JDBC URLs

JDBC uses a URL to identify the database connection.


jdbc:<subprotocol>:<subname>

Protocol

Subprotocol

Database identifier

JDBC URL with Oracle thin driver

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

jdbc:oracle:thin:@localhost:1521:XE

Using Connection
java.sql.Connection
createStatment() prepareStatment(String) prepareCall(String) commit() rollback() getMetaData()

Creating Statement Transaction Management Get database metadata Connection related

close() isClosed()

Stage 2: Query
Connect

Query

Create a statement

Process results

Query the database

Close

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

How to Query the Database


1. Create an empty statement object.
Statement stmt = conn.createStatement();

2. Execute the statement.


ResultSet rset = stmt.executeQuery(statement); int count = stmt.executeUpdate(statement); boolean isquery = stmt.execute(statement);

Querying the Database: Examples

Execute a select statement.


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

Execute a delete statement.


Statement stmt = conn.createStatement(); int rowcount = stmt.executeUpdate ("delete from ACME_RENTAL_ITEMS where rental_id = 1011");

Stage 3: Process the Results


Connect

Query Step through the results

Process results

Assign results to Java variables

Close

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.

How to Process the Results


1. Step through the result set.
while (rset.next()) { }

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


String val = rset.getString(colname); String val = rset.getString(colIndex);

while (rset.next()) { String title = rset.getString("TITLE");

String year = rset.getString("YEAR"); // Process or display the data }

Stage 4: Close
Connect

Query Close the result set Process results

Close the statement

Close

Close the connection

How to Close the Connection


1. Close the ResultSet object.
rset.close();

2. Close the Statement object.


stmt.close();

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


conn.close();

JDBC Drivers

Type 1 - JDBC-ODBC Bridge driver Type 2 - Native-API/partly Java driver Type 3 - All Java/Net-protocol driver Type 4 - Native-protocol/all-Java driver

Type 1 - JDBC-ODBC Bridge driver

The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The native database client code must be loaded on each client machine that uses this type of driver. The JDBCODBC Bridge driver is recommended only for experimental use or when no other alternative is available.

Type 1 - JDBC-ODBC Bridge driver

Advantage of Type1 driver

The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available.

Disadvantages of Type1 driver

Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types. The client system requires the ODBC Installation to use the driver. Not good for the Web.

Type 2 - Native-API/partly Java driver

The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into databasespecific calls i.e. this driver is specific to a particular database. Like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.

Type 2 - Native-API/partly Java driver

Advantage of Type2 driver

The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBCODBC Bridge as the layers of communication (tiers) are less than that of Type 1 and also it uses Native api which is Database specific.

Disadvantages of Type2 driver

Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet. Like Type 1 drivers, its not written in Java Language which forms a portability issue. If we change the Database we have to change the native API as it is specific to a database Mostly obsolete now Usually not thread safe.

Type 3 - All Java/Net-protocol driver

Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.

Type 3 - All Java/Net-protocol driver

Advantage of Type3 driver

This driver is server-based, so there is no need for any vendor database library to be present on client machines. This driver is fully written in Java and hence Portable. It is suitable for the web. There are many opportunities to optimize portability, performance, and scalability. The net protocol can be designed to make the client JDBC driver very small and fast to load.

Advantage of Type3 driver (cont)

The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced system administration such as logging and auditing. This driver is very flexible allows access to multiple databases using one driver. They are the most efficient amongst all driver types.

Disadvantages of Type3 driver

It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server.

Type 4 - Native-protocol/all-Java driver

The Type 4 drivers take JDBC calls and translates them into the network protocol using java networking libraries to communicate directly with the database server.

Type 4 - Native-protocol/all-Java driver

Advantage of Type4 driver

The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web. Number of translation layers is very less i.e. type 4 JDBC drivers don't have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good.

Advantage of Type4 driver (cont)

You don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

Disadvantages of Type4 driver

With type 4 drivers, the user needs a different driver for each database.

How to implement the Type1 Driver DSN name


Start Control Panel

Administrative Tools

Data Sources (ODBC)

User DSN

Add Finish

Code for Type1 Driver


Connection cn; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); cn = DriverManager.getConnection("jdbc:odbc:deb","scott","tiger"); //deb is the name of the DSN that is connected to the database (In this case Oracle) //2nd and 3rd arguments are username and password respectively. } catch(SQLException se) { se.printStackTrace(); } catch(ClassNotFoundException cnf) { cnf.printStackTrace(); }

You might also like