Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Module_5_JDBC API-Architecture -Drivers Database Connectivity in Java

The document provides an overview of Java Database Connectivity (JDBC), detailing its purpose, architecture, and components, including JDBC API, DriverManager, and various types of JDBC drivers. It explains the steps to connect a Java application to a database, execute SQL queries, and perform CRUD operations using JDBC interfaces and classes. Additionally, it describes the two-tier and three-tier models of JDBC architecture and lists the main interfaces and classes involved in database connectivity.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Module_5_JDBC API-Architecture -Drivers Database Connectivity in Java

The document provides an overview of Java Database Connectivity (JDBC), detailing its purpose, architecture, and components, including JDBC API, DriverManager, and various types of JDBC drivers. It explains the steps to connect a Java application to a database, execute SQL queries, and perform CRUD operations using JDBC interfaces and classes. Additionally, it describes the two-tier and three-tier models of JDBC architecture and lists the main interfaces and classes involved in database connectivity.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Course Title: Java Programming

Course Code: E1UA307C


Java Programming
Module 5
Introduction to JDBC API-JDBC Architecture - JDBC
Drivers- Database connectivity in Java
Introduction to JDBC API
• JDBC stands for Java Database Connectivity.
• JDBC is a Java API to connect and execute the query with the database.
• It is a specification from Sun Microsystems that provides a standard abstraction(API or Protocol) for
Java applications to communicate with various databases.
• The classes and interfaces of JDBC API allow the application to send requests made by users to the
specified database.
• API: stands for Application Programming Interface. It is essentially a set of rules and protocols
which transfers data between different software applications and allow different software applications
to communicate with each other. Through an API one application can request information or perform a
function from another application without having direct access to it’s underlying code or the
application data.
Purpose of JDBC :
• Enterprise applications created using the JAVA EE technology need to interact with databases to store
application-specific information.
• So, interacting with a database requires efficient database connectivity, which can be achieved by using
the ODBC(Open database connectivity) driver.
• This ODBC driver is used with JDBC to interact or communicate with various kinds of databases 2such
as Oracle, MS Access, Mysql, and SQL server database.
Components of JDBC :
1. JDBC API: It provides various methods and interfaces for easy communication with the database. It
provides two packages:
java.sql: This package provides APIs for data access and data process
in a relational database, included in Java Standard Edition (java SE)
javax.sql: This package extends the functionality of java package by
providing data source interface for establishing connection pooling,
statement pooling with a data source, included in Java Enterprise
Edition (java EE)
2. JDBC Driver manager: It loads a database-specific driver in an application to establish a connection
with a database. It is used to make a database-specific call to the database to process the user request.
3. JDBC Test suite: It is used to test the operation(such as insertion, deletion, update) being performed
by JDBC Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge translates the
JDBC method call to the ODBC function call. It makes use of the sun.jdbc.odbc package which includes
a native library to access ODBC characteristics.
3
Architecture of JDBC
• Description:
1. Application: It is a java program or a servlet that
communicates with a data source.
2. JDBC API: JDBC API allows Java programs to execute
SQL statements and retrieve results.
Some of the important interfaces defined in JDBC API are as
follows: Driver interface, ResultSet Interface, RowSet
Interface, PreparedStatement interface, Connection
inteface, and Classes defined in JDBC API are as follows:
DriverManager class, Types class, Blob class, clob class.
3. DriverManager: It plays an important role in the JDBC
architecture. It uses some database-specific drivers to
effectively connect enterprise applications to databases.
4. JDBC drivers: To communicate with a data source through
JDBC, you need a JDBC driver that intelligently
communicates with the respective data source.

4
General Architecture JDBC-to-database

Java Application

JDBC API

Driver Manager

JDBC Driver API

JDBC / ODBC Vendor supplied


Bridge JDBC Driver

ODBC Driver

Database
Database
Types of JDBC Architecture(2-tier and 3-tier)
• The JDBC architecture consists of two-tier and three-tier processing models to access a database.
They are as described below:
1. Two-tier model: A java application communicates directly to the data source. The JDBC driver
enables the communication between the application and the data source.
• When a user sends a query to the data source, the answers for those queries are sent back to the user in
the form of results. The data source can be located on a different machine on a network to which a
user is connected.
• This is known as a client/server configuration, where the user’s machine acts as a client, and the
machine has the data source running acts as the server.

Figure 1: Two-tier Architecture for Data Access. 6


2. Three-tier model: In this, the user’s queries are sent to middle-tier services, from which the
commands are again sent to the data source.
The results are sent back to the middle tier, and from there to the user.

Figure 2: Three-tier Architecture for Data Access.


7
JDBC Drivers
• JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert
requests from Java programs to a protocol that the DBMS can understand.
• There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver (partially java driver)
3. Type-3 driver or Network Protocol driver (fully java driver)
4. Type-4 driver or Thin driver (fully java driver)

8
1) JDBC-ODBC bridge driver
• 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.

In Java 8, the JDBC-ODBC Bridge has been


removed. 9
2) Native-API driver
• The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API.
• It is not written entirely in java.

10
3) Network Protocol driver
• 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.

11
4) Thin driver
• 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.

12
Interfaces and Classes of JDBC API
A list of popular interfaces of JDBC API is given below:
• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
Classes of JDBC API:
• ResultSet interface
A list of popular classes of JDBC API is given below:
• ResultSetMetaData interface
•DriverManager class
• DatabaseMetaData interface
• RowSet interface •Blob class

•Clob class

•Types class

13
Database connectivity or JDBC Connection in Java
• Database connectivity or JDBC Connection means Establishing a connection between : the front end i.e
your Java Program and the back end i.e the database.

Steps to Connect Java Application with Database:


Step 1 – Import the Packages:
import java.sql.*;
Step 2 – Load the drivers using the forName() method
Class.forName("com.mysql.cj.jdbc.Driver"); // Driver name
Step 3– Establish a connection using the Connection Interface and DriverManager class
Connection con = DriverManager.getConnection(url, username, password);

• user: Username from which your SQL command prompt can be accessed.
• password: password from which the SQL command prompt can be accessed.
• con: It is a reference to the Connection interface.
• Url: Uniform Resource Locator which is created as shown below:
String url = "jdbc:mysql://localhost:3306/university";
14
Cont..
Step 4 – Create a statement : Once a connection is established you can interact with the database. The
JDBCStatement, CallableStatement, and PreparedStatement interfaces define the methods that enable
you to send SQL commands and receive data from your database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();

Step 5 – Execute the query: Now comes the most important part i.e executing the query. The query here
is an SQL Query. Now we know we can have multiple types of queries.
Some of them are as follows:
• The query for updating/inserting a table in a database.
• The query for retrieving data.

The executeQuery() method of the Statement interface is used to execute queries of retrieving values
from the database. This method returns the object of ResultSet that can be used to get all the records of a
table.
The executeUpdate(sql query) method of the Statement interface is used to execute queries of
updating/inserting. 15
Cont..
• Step 6 – Close the connections
resultSet.close();
statement.close();
connection.close();

16
Understand the main JDBC interfaces and classes
• Let’s take an overview look at the JDBC’s main interfaces and classes with which we usually work. They are
all available under the java.sql package:
• DriverManager: this class is used to register driver for a specific database type (e.g. MySQL in this tutorial)
and to establish a database connection with the server via its getConnection() method.
• Connection: this interface represents an established database connection (session) from which we can create
statements to execute queries and retrieve results, get metadata about the database, close connection, etc.
• Statement and PreparedStatement: these interfaces are used to execute static SQL query and
parameterized SQL query, respectively. Statement is the super interface of the PreparedStatement interface.
Their commonly used methods are:
1. boolean execute(String sql): executes a general SQL statement. It returns true if the query returns
a ResultSet, false if the query returns an update count or returns nothing. This method can be used
with a Statement only.
2. int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE statement and returns
an update account indicating number of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0
rows affected).
3. ResultSet executeQuery(String sql): executes a SELECT statement and returns a ResultSet object
which contains results returned by the query 17
Cont..
• A prepared statement is one that contains placeholders (in form question marks ?) for dynamic
values will be set at runtime. For example:
• SELECT * from Users WHERE user_id=?

• Here the value of user_id is parameterized by a question mark and will be set by one of
the setXXX() methods from the PreparedStatement interface, e.g. setInt(int index, int value).
• ResultSet: contains table data returned by a SELECT query. Use this object to iterate over rows in the
result set using next() method, and get value of a column in the current row using getXXX() methods
(e.g. getString(), getInt(), getFloat() and so on). The column value can be retrieved either by index
number (1-based) or by column name.
• SQLException: this checked exception is declared to be thrown by all the above methods, so we have
to catch this exception explicitly when calling the above classes’ methods.

18
CRUD Operation with JDBC
• the steps of setting up a simple CRUD (create or insert, read, update, delete) operation using JDBC.
1. Create a new record: We can use the connection object to create a new record in the database. To
do this, we will need to use an SQL INSERT statement and execute it using the connection object.
Using PreparedStatement Interface:
try {
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?,
?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, "value1");
statement.setString(2, "value2");
statement.setInt(3, 123);
statement.executeUpdate();
System.out.println("Record created.");
} catch (SQLException e) {
e.printStackTrace();
} 19
Using Statement interface:
public static void createData(){
final String url = "jdbc:mysql://localhost:3306/employeedb";
final String uname = "root";
final String pass = "";
Scanner sc = new Scanner(System.in);
System.out.println("\t\t\t*Please Remember 'Your ID' number for further
Updatation.....");
System.out.print("\t\t\tEnter employee ID number : ");
int id = sc.nextInt();
System.out.print("\t\t\tEnter employee name : ");
String name = sc.next();
System.out.print("\t\t\tEnter employee department : ");
String department = sc.next();
System.out.print("\t\t\tEnter employee Location : ");
String location = sc.next();
String query="INSERT INTO employees (id, name, department, location) values
('"+id+"','"+name+"','"+department+"','"+location+"')";

20
try{
Connection con=DriverManager.getConnection(url,uname,pass);
Statement stmt = con.createStatement();
int rows = stmt.executeUpdate(query);
if(rows==1) {
System.out.println("\t\t\t rows affected....");
}else {
System.out.println("\t\t\tSomething is Wrong.....!! ");
}

}catch (Exception e){


e.printStackTrace();

}
}

21
2. Read a record:
To read a record from the database, you will need to use an SQL SELECT statement and execute it using
the connection object. The result of the query will be a ResultSet object that you can use to access the
data in the record.

try {
String sql = "SELECT column1, column2, column3 FROM table_name WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 1);
ResultSet result = statement.executeQuery();
if (result.next()) {
String column1 = result.getString("column1");
String column2 = result.getString("column2");
int column3 = result.getInt("column3");
System.out.println("Column 1: " + column1);
System.out.println("Column 2: " + column2);
System.out.println("Column 3: " + column3);
}
} catch (SQLException e) {
e.printStackTrace();
}
22
3. Update a record:
To update a record in the database, you will need to use an SQL UPDATE statement and execute it using
the connection object.
try {
String sql = "UPDATE table_name SET column1 = ?, column2 = ?, column3 = ?
WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, "new_value1");
statement.setString(2, "new_value2");
statement.setInt(3, 456);
statement.setInt(4, 1);
statement.executeUpdate();
System.out.println("Record updated.");
} catch (SQLException e) {
e.printStackTrace();
} 23
4. Delete a record:
To delete a record from the database, you will need to use an SQL DELETE statement and execute it
using the connection object.
try {
String sql = "DELETE FROM table_name WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 1);
statement.executeUpdate();
System.out.println("Record deleted.");
} catch (SQLException e) {
e.printStackTrace();
}

24
T
• has

25
T
• has

26
T
• has

27
T
• has

28

You might also like