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

Unit 3_JDBC

Uploaded by

fortiratra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Unit 3_JDBC

Uploaded by

fortiratra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

JDBC Database Connectivity

Enterprise Application Development

Bhupendra Panchal

4/18/2023 1
Outlines
• JDBC Using Relational Databases: Introduction
• Best Practices for Programming for Databases
• JDBC Drivers for RDBM Systems
• SQL to Java Type Mapping
• Using the java.sql API
• Coding Transactions
• Using the Javax.sql API
• Connection pooling

4/18/2023 2
Topics
• Overview
– JDBC
– Types of Drivers
– API
• Connecting to Databases
• Executing Queries & Retrieving Results
• Advanced Topics
– Prepared Statements
– Connection Pooling
• Assignment
4/18/2023 3
Overview

4/18/2023 4
JDBC: Definition
• JDBC: Java Database Connectivity
– JDBC is a Java API to connect and execute the query with the
database. It is a part of JavaSE (Java Standard Edition).
– It provides a standard library for Java programs to connect to a
database and send it commands using SQL.
– It generalizes common database access functions into a set of
common classes and methods.

4/18/2023 7
JDBC: API
Why Should We Use JDBC?
• Before JDBC, ODBC API was the database API to connect and execute the
query with the database. But, ODBC API uses ODBC driver which is written in
C language (i.e. platform dependent and unsecured). That is why Java has
defined its own API (JDBC API) that uses JDBC drivers (written in Java
language).

We can use JDBC API to handle database using Java program and can perform the
following activities:
• Connect to the database
• We can use JDBC API to access tabular data stored in any relational database.
• By the help of JDBC API, we can save, update, delete and fetch data from the
database.
• It is like Open Database Connectivity (ODBC) provided by Microsoft.

4/18/2023 8
JDBC: API
• API (Application programming interface) is a document that contains a
description of all the features of a product or software.
• It represents classes and interfaces that software programs can follow to
communicate with each other.
• An API can be created for applications, libraries, operating systems, etc.

JDBC API Standardizes:


– JDBC API uses JDBC drivers to connect with the database.
– Approach to initiating queries
– Method to create stored procedures
– Execute queries and update statements to the database
– Retrieve the result received from the database.

4/18/2023 9
JDBC: API
• Two main packages java.sql and javax.sql
– Java.sql contains all core classes required for accessing database
(Part of Java 2 SDK, Standard Edition)
– Javax.sql contains optional features in the JDBC 2.0 API
(part of Java 2 SDK, Enterprise Edition)

• Javax.sql adds functionality for enterprise applications


– DataSources
– Connection Pooling
– Rowsets
– Distributed Transactions

4/18/2023 10
JDBC: Architecture
• JDBC Consists of two parts:
– JDBC API, a purely Java-based
API
– JDBC Driver Manager, which
communicates with vendor-
specific drivers that perform the
real communication with the
database

• Translation to the vendor format


occurs on the client
– No changes needed to the server
– Driver (translator) needed on
client

4/18/2023 11
JDBC: Architecture

4/18/2023 12
JDBC: Interfaces & Classes
A list of popular interfaces of A list of popular classes of
JDBC API are: JDBC API are:
Driver interface DriverManager class
Connection interface Blob class
Statement interface Clob class
PreparedStatement interface Types class
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface

4/18/2023 13
JDBC: Drivers
• JDBC Driver is a software component that enables java application
to interact with the database.
• JDBC uses drivers to translate generalized JDBC calls into vendor-
specific database calls

There are 4 types of JDBC drivers:

• JDBC-ODBC bridge driver


• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• Thin driver (fully java driver)

4/18/2023 14
JDBC: JDBC-ODBC bridge driver (Type I)
• Type I driver provides mapping between JDBC and access API of a database
– The access API calls the native API of the database to establish communication
• A common Type I driver defines a JDBC to ODBC bridge
– ODBC is the database connectivity for databases
– JDBC driver translates JDBC calls to corresponding ODBC calls
– Thus if ODBC driver exists for a database this bridge can be used to
communicate with the database from a Java application
• Inefficient and narrow solution
– Inefficient, because it goes through multiple layers
– Narrow, since functionality of JDBC code limited to whatever ODBC supports
Driver (Type I)

ODBC API
Native API
Client
Application API Protocol Database Specific Database
Protocol

4/18/2023 15
JDBC: JDBC-ODBC bridge driver (Type I)
• The JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls into
the ODBC function calls. This is now discouraged because of thin driver.
• Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle
recommends that you use JDBC drivers provided by the vendor of your
database instead of the JDBC-ODBC Bridge.

4/18/2023 16
JDBC: JDBC-ODBC bridge driver (Type I)
Advantages:
1. Easy to use.
2. No need to install separately, since it is provided by Sun
Microsystem so it is part of JDK.
3. Database Independent : can be easily connected to any database

Disadvantages:
1.Performance degraded because JDBC method call is converted into
the ODBC function calls. (Called Snail Driver)
2.The ODBC driver needs to be installed on the client machine.
3. Platform dependent because it is provided by Microsoft (Only for Windows)
4. Supports upto JAVA 1.7 version only.

4/18/2023 17
JDBC:
Native-API driver (partially java driver) (Type II)
• Type II driver communicates directly with native API
– Type II makes calls directly to the native API calls
– More efficient since there is one less layer to contend with
(i.e. no ODBC)
– It is dependent on the existence of a native API for a
database
Driver (Type II)

Native API
Client
Application Database
API Protocol Database Specific
Protocol

4/18/2023 18
JDBC:
Native-API driver (partially java driver) (Type II)

Advantage:
•performance upgraded than JDBC-ODBC bridge driver.
•Portability is more. Can support windows, linux etc.

Disadvantage:
•Database dependent (if you change database, change the driver)
•Platform dependent (if you change platform, change the driver)
4/18/2023 19
•The Vendor client library needs to be installed on client machine.
JDBC
Network Protocol driver (fully java driver) (Type III)
• Type III driver make calls to a middleware component running on
another server
– This communication uses a database independent net protocol
– Middleware server then makes calls to the database using database-
specific protocol
– The program sends JDBC call through the JDBC driver to the middle
tier
– Middle-tier may use Type I or II JDBC driver to communicate with
the database.
Driver (Type III)

Client Middleware
Application Net Protocol Server Database Specific Database
Protocol

4/18/2023 20
JDBC
Network Protocol driver (fully java driver) (Type III)

The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. It is fully written in
java.

4/18/2023 21
JDBC
Network Protocol driver (fully java driver) (Type III)

Advantage:
•No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:
•Network support is required on client machine.
•Requires database-specific coding to be done in the middle tier.
•Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

4/18/2023 22
JDBC:
Thin driver (fully java driver) (Type IV)

Type IV driver is an all-Java driver that is also called a thin driver


– It issues requests directly to the database using its native protocol
– It can be used directly on platform with a JVM
– Most efficient since requests only go through one layer
– Simplest to deploy since no additional libraries or middle-ware

Driver (Type IV)

Client
Application Database Specific Database
Protocol

4/18/2023 23
JDBC:
Thin driver (fully java driver) (Type IV)
The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in Java
language.

Advantage:
• Pure Java Driver so it is platform
independent driver.
• Better performance than all other
drivers because of less conversion.
• No ODBC/ Native library/
middleware software is required at
client side or server side.

Disadvantage:
• Drivers depend on the Database.
4/18/2023 24
Connecting to Database

4/18/2023 25
Java Database Connectivity

There are 5 steps to connect any java application with the database using JDBC.

These steps are as follows:

1.Register the Driver class


2.Create connection
3.Create statement
4.Execute queries
5.Close connection
JDBC: Conceptual Components
• Driver Manager: Loads database drivers and manages connections
between the application and the driver
• Driver: Translates API calls into operations for specific database
• Connection: Session between application and data source
• Statement: SQL statement to perform query or update
• Metadata: Information about returned data, database, & driver
• Result Set: Logical set of columns and rows of data returned by
executing a statement

Creates Creates Creates


DriverManager Connection Statement Result Set

Driver
Established
Link to DB

Database
4/18/2023 27
1. Driver Manager Class
Register the DriverManager class

• The DriverManager class is the component of JDBC API and also a


member of the java.sql package.

• It acts as an interface between users and drivers. It keeps track of the


drivers that are available and handles establishing a connection
between a database and the appropriate driver.

• The forName() method of Class is used to register the driver class. This
method is used to dynamically load the driver class.

Syntax of forName() method

public static void forName(String className)throws ClassNotFoundExcepti


on
JDBC Driver Loading: class.forName()

public static void main(String args[]){


try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

}
catch(Exception e)
{ System.out.println(e);}
}
}

4/18/2023 29
2. Connection Interface
Create the connection object
• A Connection is a session between a Java application and a database. It
helps to establish a connection with the database.

• The Connection interface is a factory of Statement, PreparedStatement,


and DatabaseMetaData, i.e., an object of Connection can be used to get
the object of Statement and DatabaseMetaData.

• The Connection interface provide many methods for transaction


management like commit(), rollback(), setAutoCommit(),
setTransactionIsolation(), etc.

• The getConnection() method of DriverManager class is used to establish


connection with the database.

Syntax of getConnection() method


public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password) throws S
QLException
Connection: Creation
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system",“123");

}
catch(Exception e)
{ System.out.println(e);}
}
}
4/18/2023 31
3. Statement Object
Create the Statement object

• The createStatement() method of Connection interface is used to create


statement.
• The object of statement is responsible to execute queries with the
database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException

Example to create the statement object

Statement stmt=con.createStatement();
Statement: Syntax
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system",“123");

//step3 create the statement object


Statement stmt=con.createStatement();
}
catch(Exception e)
{ System.out.println(e);}
}
}
4/18/2023 33
4. Result Set
Execute the query

• The executeQuery() method of Statement interface is used to execute


queries to the database.
• This method returns the object of ResultSet that can be used to get all
the records of a table.

Syntax of executeQuery() method

public Statement createStatement()throws SQLException

Example to execute query

ResultSet rs=stmt.executeQuery("select * from emp");


while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Executing Queries: Methods
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system",“123");

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
catch(Exception e)
{ System.out.println(e);}
}
} 4/18/2023 35
Executing Queries
Data Definition Language (DDL)
• Data definition language queries use executeUpdate
• Syntax: int executeUpdate(String sqlString) throws SQLException
– It returns an integer which is the number of rows updated
– sqlString should be a valid String else an exception is thrown
• Example 1: Create a new table
Statement statement = connection.createStatement();
String sqlString =
“Create Table Catalog”
+ “(Title Varchar(256) Primary Key Not Null,”+
+ “LeadActor Varchar(256) Not Null, LeadActress Varchar(256) Not Null,”
+ “Type Varchar(20) Not Null, ReleaseDate Date Not NULL )”;
Statement.executeUpdate(sqlString);
– executeUpdate returns a zero since no row is updated

4/18/2023 36
Executing Queries
DDL (Example)
• Example 2: Update table
Statement statement = connection.createStatement();
String sqlString =
“Insert into Catalog”
+ “(Title, LeadActor, LeadActress, Type, ReleaseDate)”
+ “Values(‘Gone With The Wind’, ‘Clark Gable’, ‘Vivien Liegh’,”
+ “’Romantic’, ‘02/18/2003’ ”
Statement.executeUpdate(sqlString);
– executeUpdate returns a 1 since one row is added

4/18/2023 37
Executing Queries
Data Manipulation Language (DML)
• Data definition language queries use executeQuery
• Syntax
ResultSet executeQuery(String sqlString) throws SQLException
– It returns a ResultSet object which contains the results of the Query
• Example 1: Query a table
Statement statement = connection.createStatement();
String sqlString = “Select Catalog.Title, Catalog.LeadActor, Catalog.LeadActress,” +
“Catalog.Type, Catalog.ReleaseDate From Catalog”;
ResultSet rs = statement.executeQuery(sqlString);

4/18/2023 38
Java Database Connectivity
5) Close the connection object

By closing connection object statement and ResultSet will be closed


automatically. The close() method of Connection interface is used to close
the connection.

Syntax of close() method

public void close()throws SQLException

Example to close connection

con.close();
Source Code

4/18/2023 40
Requirement to perform JDBC
1. JDK
2. JAVA IDE such as
– Eclipse IDE, Netbeans etc
– Any text editor such as Notepad, VSCode etc.
3. Database Software such as Oracle 11g/MySQL
4. Download the jar file
– ojdbc14.jar for Oracle
– mysql-connector-java-8.0.22 for MySQL
Java Database Connectivity with Oracle
To connect java application with the oracle database, we need to follow 5
following steps. In this example, we are using Oracle 11g as the database. So we
need to know following information for the oracle database:

1. Driver class: The driver class for the oracle database


is oracle.jdbc.driver.OracleDriver.

2. Connection URL: The connection URL for the oracle10G database


is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the
database, thin is the driver, localhost is the server name on which oracle is
running, we may also use IP address, 1521 is the port number and XE is the
Oracle service name. You may get all these information from the tnsnames.ora file.

3. Username: The default username for the oracle database is system.

4. Password: It is the password given by the user at the time of installing the oracle
database.

5. Create a Table: Before establishing connection, let's first create a table in oracle
database. Following is the SQL query to create a table.

create table emp(id number(10),name varchar2(40),age number(3));


Java Database Connectivity with Oracle
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system",“123");

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

//step5 close the connection object


con.close();
}
catch(Exception e)
{ System.out.println(e);}
}
}
Java Database Connectivity with Oracle
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.

package JDBCDemo;

import java.sql.*;
public class JDBC_Connect {

public static void main(String[] args) {


try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","123");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Java Database Connectivity with MySQL
package JDBCDemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBC_Connect_SQL {
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","root");
//db is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");

while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}

}
Advanced Topics

4/18/2023 46
SQL to Java Type Mapping
When you retrieve data from a database into an iterator object (see Result
sets) or into a host variable, you must use Java™ types that are compatible
with the SQL types. The following table shows valid conversions from SQL
types to Java types.
SQL type Java type
BIGINT, BIGSERIAL bigint
BOOLEAN boolean
BYTE byte[]
CHAR, CHARACTER String
DATE java.sql.Date
DATETIME java.sql.Timestamp
FLOAT, DOUBLE double
INTEGER, INT int
TEXT String
VARCHAR String
SQL to Java Type Mapping
Let us see with an example for the ’employee’ We can map these employee attributes in SQL
class in java Server tables easily. Let us see how to do that

public class Employee {


CREATE TABLE [Employee] (
//identify the employee uniquely
[id] INT NOT NULL, -- Primary
private int id;
Key and hence not null
[firstName] VARCHAR (20) NULL,
// firstName of an employee
[lastName] VARCHAR (20) NULL,
private String firstName;
[salary] INT NULL,
// lastName of an employee [qualification] VARCHAR (50) NULL,
private String lastName; );

// salary of an employee
private int salary;

// qualification of an employee
private String qualification;

//.....

}
SQL to Java Type Mapping using java.sql
• The java.sql package provides the API for accessing and processing data
stored in a data source (usually a relational database) using the Java
programming language.
• The java.sql package contains the entire JDBC API that sends SQL
(Structured Query Language) statements to relational databases and retrieves
the results of executing those SQL statements.
• This API includes a framework whereby different drivers can be installed
dynamically to access different data sources.

• Interfaces provided by java.sql package:


– Connection
– Statement
– Prepared Statement
– Result Set
– ResultSet Metadata
SQL to Java Type Mapping using java.sql
The various classes in the package are shown below:
Class Description
Date It gives time in milliseconds. It provides sql with dates. The class is
declared as:
public class Date extends Date
DriverManager The class is designed for managing the various JDBC drivers. The class is
declared as follows:
public class DriverManager extends Object
DriverPropertyInfo The class keeps an account for making a secure connection. The class is
declared as follows:
public class DriverPropertyInfo extends Object
SQLPermission The class manages the various SQL related permissions which are
provided to the accessing objects. The class is declared as follows:
public final class SQLPermission extends BasicPermission
Time The class provides time related information. The class is declared as
follows:
public class Time extends Date
Timestamp The class allows JDBC API to identify as TIMESTAMP value. The class is
declared as follows:
public class Timestamp extends Date
Types The class defines various SQL constants. The class is declared as follows:
public class Types extends Object
SQL to Java Type Mapping using javax.sql
• java.sql.* --> This package is used for the basic JDBC connections.
• javax.sql.* --> This package provides advance JDBC features such as
connection pooling, distributed transaction, disconnected row sets

Connection Pooling
• A JDBC connection pool is a group of reusable connections for a particular
database. Because creating each new physical connection is time consuming,
the server maintains a pool of available connections to increase performance.
When an application requests a connection, it obtains one from the pool.
• Connection pooling is a well-known data access pattern. Its main purpose is to
reduce the overhead involved in performing database connections and
read/write database operations.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy