0% found this document useful (0 votes)
16 views27 pages

Chapter 4JDBC

This document provides an overview of Database Connectivity in Java, focusing on JDBC architecture, driver types, and configuration. It covers key concepts such as DDL and DML operations, SQL exceptions, and transaction management. Additionally, it discusses various JDBC components like ResultSet, PreparedStatement, and RowSet, along with examples and syntax for database operations.

Uploaded by

14depace
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)
16 views27 pages

Chapter 4JDBC

This document provides an overview of Database Connectivity in Java, focusing on JDBC architecture, driver types, and configuration. It covers key concepts such as DDL and DML operations, SQL exceptions, and transaction management. Additionally, it discusses various JDBC components like ResultSet, PreparedStatement, and RowSet, along with examples and syntax for database operations.

Uploaded by

14depace
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

Database Connectivity (4 Hrs.

)
BSc. CSIT 7th Semester
Chapter - 4

Er. Jeewan Rai


Computer Engineering (Bachelor)
Master in Information System Engineering (Master)
Contents
4.1. JDBC Architecture, JDBC Driver Types, JDBC Configuration, Managing
Connections, Statements, Result Set, SQL Exceptions
Chapter – 4 : Database Connectivity (4 Hrs.)

4.2. DDL and DML Operations using Java, Prepared Statements, Multiple
Advanced JAVA Programming

Results, Scrollable Result Sets, Updateable Result Sets, Row Sets and Cached
Row Sets, Transactions, SQL Escapes.

12/10/2023 Er. Jeewan Rai 2


JDBC Introduction
• JDBC stands for Java Database Connectivity.
• JDBC is a Java API to connect and execute the query with the database.
Chapter – 4 : Database Connectivity (4 Hrs.)

• It is a part of JavaSE (Java Standard Edition).


• JDBC API uses JDBC drivers to connect with the database.
Advanced JAVA Programming

• There are four types of JDBC drivers:


a) JDBC-ODBC Bridge Driver: uses ODBC driver to connect to the database
b) Native Driver (Partially Java Driver): uses the client-side libraries of the database
c) Network Protocol Driver (Fully Java Driver): uses middleware (application server)
d) Thin Driver (Fully Java Driver): JDBC calls directly into the vendor-specific database

12/10/2023 Er. Jeewan Rai 3


Advanced JAVA Programming
Chapter – 4 : Database Connectivity (4 Hrs.)

12/10/2023
JDBC Architecture

Er. Jeewan Rai


4
JDBC Configuration
• [Link]
Chapter – 4 : Database Connectivity (4 Hrs.)
Advanced JAVA Programming

12/10/2023 Er. Jeewan Rai 5


Java Database Connectivity Steps
1. Register the Driver class

2. Create connection
Chapter – 4 : Database Connectivity (4 Hrs.)

3. Create statement
Advanced JAVA Programming

4. Execute queries

5. Close connection

[Link]

12/10/2023 Er. Jeewan Rai 6


SQL Exception
• The SQLException class and its subtypes provide information about errors
and warnings that occur while a data source is being accessed.
Chapter – 4 : Database Connectivity (4 Hrs.)

• The base class for exceptions that occur while running JDBC applications is
SQLException.
Advanced JAVA Programming

• the following information is available from an SQLException:


a) Text description e.g. Divide by zero error encountered.
b) SQLState e.g. warning, connection failure
c) Error code e.g. 011 = connection not closed, 105 = invalid string
d) A reference to any other exceptions that also occurred

[Link]

12/10/2023 Er. Jeewan Rai 7


DDL and DML
SN Key DDL DML
Stands for DDL stands for Data Definition Language. DML stands for Data Manipulation
1
Chapter – 4 : Database Connectivity (4 Hrs.)

Language.
Usage DDL statements are used to create database, DML statement is used to insert, update
2
schema, constraints, users, tables etc. or delete the records.
Advanced JAVA Programming

Classification DDL has no further classification. DML is further classified into procedural
3
DML and non-procedural DML.
4 Commands CREATE, DROP, RENAME, ALTER. INSERT, SELECT, UPDATE, DELETE.

12/10/2023 Er. Jeewan Rai 8


DDL
Create Table Drop table
CREATE TABLE DDL DROP TABLE DDL;
(
Chapter – 4 : Database Connectivity (4 Hrs.)

id int, Rename table


DDL_Type varchar(50),
RENAME TABLE table_name TO NEW table_name
DDL_Value int
);
Advanced JAVA Programming

Add New Column Rename column

ALTER TABLE DDL ALTER TABLE table_name RENAME COLUMN


ADD COLUMN DDL_Example varchar(50); old_column_name TO new_column_name;

Change Column Datatype


ALTER TABLE DDL
MODIFY DDL_Example BIGINT;

12/10/2023 Er. Jeewan Rai 9


DML
INSERT

INSERT INTO DDL (id, DDL_Type, DDL_Value)


Chapter – 4 : Database Connectivity (4 Hrs.)

VALUES (2, 'DML', 123), (3, 'DCL', 123);

SELECT
Advanced JAVA Programming

SELECT * FROM DDL

UPDATE

UPDATE ddl
SET DDL_Value = 555 WHERE DDL_Type = 'DML';

DELETE
DELETE FROM DDL
Where id = 2

12/10/2023 Er. Jeewan Rai 10


ResultSet interface
• The object of ResultSet maintains a cursor pointing to a row of a table.

• Initially, cursor points to before the first row.


Chapter – 4 : Database Connectivity (4 Hrs.)
Advanced JAVA Programming

12/10/2023 Er. Jeewan Rai 11


import [Link].*; Select name of countries form countries table
static final String JDBC_DRIVER = "[Link]";
static final String DB_URL = "jdbc:mysql://localhost:3306/";
static final String DB = "breath_fresh3";
static final String DB_USER = "root";
static final String DB_PASS = "";
Chapter – 4 : Database Connectivity (4 Hrs.)

public static void main(String[] args) throws SQLException, ClassNotFoundException{

Connection conn=null;
ResultSet rs = null;
Advanced JAVA Programming

Statement stmt = null;


try {
// Open a connection
[Link]("Connecting ...");
conn = [Link]( DB_URL + DB, DB_USER, DB_PASS);
if (conn != null) {
[Link]("Connected Successfully.");
}
//int result=[Link]("delete from emp765 where id=33");
stmt = [Link]();
rs = [Link]("select * from countries");
while ([Link]())
[Link]([Link]("name"));

} catch (SQLException ex) {


[Link]([Link]());
}
}
12/10/2023 Er. Jeewan Rai 12
JDBC API Interface: Statement vs PreparedStatement
• Statement – Used to execute string-based SQL queries

Syntax
Chapter – 4 : Database Connectivity (4 Hrs.)

Statement stmt = [Link]( );

String SQL = "Update Employees SET age = 55 WHERE id = 5" ;


Advanced JAVA Programming

[Link](SQL);

• PreparedStatement – Used to execute parameterized SQL queries

Syntax:

String SQL = "Update Employees SET age = ? WHERE id = ?" ;

PreparedStatement updateSales = [Link] (SQL);

[Link](1, 55);

[Link](2, 5);

[Link]();

12/10/2023 Er. Jeewan Rai 13


Understanding RowSet
• A row set contains all data from a result set, but it can be disconnected
from the database. A rowset may make a connection with a database and
Chapter – 4 : Database Connectivity (4 Hrs.)

keep the connection open during its life cycle, in which case it is
called connected rowset.
Advanced JAVA Programming

• A row set may also make connection with a database, get data from it, and
then close the connection. Such a row set is called disconnected rowset.
• In JDBC, a row set is represented by the RowSet interface which is defined
in the [Link] package. The [Link] package is an extension of JDBC,
besides the primary package [Link].

12/10/2023 Er. Jeewan Rai 14


RowSet interface
• A CachedRowSet stores data in memory so you can work on the data
without keeping the connection open all the time. CachedRowSet is the
Chapter – 4 : Database Connectivity (4 Hrs.)

super interface of the ones below.


• A FilteredRowSet allows filtering data without having to write SQL SELECT
Advanced JAVA Programming

queries.
• A JoinRowSet combines data from different RowSet objects, which is
equivalent to SQL JOIN queries.
• A JdbcRowSet is a thin wrapper around a ResultSet that makes it possible
to use the result set as a JavaBeans component.
• A WebRowSet can read and write data in XML format, making it possible to
transfer the data through tiers in a web application.
12/10/2023 [Link]
Er. Jeewan Rai 15
Scrollable ResultSet
• A scrollable ResultSet is one which allows us to retrieve the data in forward
direction as well as backward direction
Chapter – 4 : Database Connectivity (4 Hrs.)

PreparedStatement statement = [Link](


String sql, int resultSetType, int resultSetConcurrency);
Advanced JAVA Programming

The possible values for resultSetType and resultSetConcurrency are defined


by some constants in the ResultSet interface

12/10/2023 Er. Jeewan Rai 16


Advanced JAVA Programming
Chapter – 4 : Database Connectivity (4 Hrs.)

12/10/2023
Er. Jeewan Rai
Example: Scrollable Result Sets

17
Update ResultSet
Update Result Set is used for following operation
•inserting a record,
Chapter – 4 : Database Connectivity (4 Hrs.)

•deleting a record and


•updating a record.
Advanced JAVA Programming

Syntax:

Statement st=[Link] (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

12/10/2023 Er. Jeewan Rai 18


Advanced JAVA Programming
Chapter – 4 : Database Connectivity (4 Hrs.)

12/10/2023
Er. Jeewan Rai
Example: Update Resultset

19
ResultSet Type Values
• You can create a Statement that returns result sets in one of the following
types:
Chapter – 4 : Database Connectivity (4 Hrs.)

• - TYPE_FORWARD_ONLY: the result set is not scrollable (default).


• - TYPE_SCROLL_INSENSITIVE: the modifications done in the database are
Advanced JAVA Programming

not reflected in the ResultSet.


• - TYPE_SCROLL_SENSITIVE: the modifications done in the database are
reflected in the ResultSet.

12/10/2023 Er. Jeewan Rai 20


ResultSet Concurrency Values
• A Statement can return result sets which are read-only or updatable,
specified by one of the following constants defined in
the ResultSet interface:
Chapter – 4 : Database Connectivity (4 Hrs.)

• - CONCUR_READ_ONLY: the result set cannot be used to update the


database (default).
Advanced JAVA Programming

• - CONCUR_UPDATABLE: the result set can be used to update the database.

Statement statement = [Link](


ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

[Link]

12/10/2023 Er. Jeewan Rai 21


Methods to scroll through the result set:
- first(): moves the cursor to the first row.

- next(): moves the cursor forward one row from its current position.
Chapter – 4 : Database Connectivity (4 Hrs.)

- previous(): moves the cursor to the previous row.


Advanced JAVA Programming

- relative(int rows): moves the cursor a relative number of rows from its
current position. The value of rows can be positive (move forward) or
negative (move backward).

- absolute(int row): moves the cursor to the given row number.

12/10/2023 Er. Jeewan Rai 22


SQL Escapes
• The escape syntax gives you the flexibility to use database specific features unavailable to you by using
standard JDBC methods and properties.
• SQL escape syntax
Chapter – 4 : Database Connectivity (4 Hrs.)

• {keyword 'parameters'}
//Create a Statement object
stmt = [Link]();
Advanced JAVA Programming

//Insert data ==> ID, First Name, Last Name, DOB


String sql="INSERT INTO STUDENTS VALUES" + "(100,'Zara','Ali', {d '2001-12-16'})";
[Link](sql);

escape Keyword
String sql = "SELECT symbol FROM MathSymbols WHERE symbol LIKE '\%' {escape '\'}";
[Link](sql);

12/10/2023 Er. Jeewan Rai 23


Transaction Management in JDBC
• Transaction represents a single unit of work.
• The ACID properties describes the transaction management well. ACID
Chapter – 4 : Database Connectivity (4 Hrs.)

stands for Atomicity, Consistency, isolation and durability.


• Atomicity means either all successful or none.
Advanced JAVA Programming

• Consistency ensures bringing the database from one consistent state to


another consistent state.
• Isolation ensures that transaction is isolated from other transaction.
• Durability means once a transaction has been committed, it will remain so,
even in the event of errors, power loss etc.

12/10/2023 Er. Jeewan Rai 24


Connection interface
• fast performance It makes the performance fast because database is hit at
the time of commit.
Chapter – 4 : Database Connectivity (4 Hrs.)
Advanced JAVA Programming

Method Description

void setAutoCommit (boolean It is true bydefault means each transaction is committed


status) bydefault.
void commit() commits the transaction.
void rollback()
12/10/2023
cancels the transaction.
Er. Jeewan Rai 25
Example of transaction management in jdbc using Statement
import [Link].*;
class FetchRecords{
public static void main(String args[])throws Exception{
Chapter – 4 : Database Connectivity (4 Hrs.)

[Link]("[Link]");
Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe","system","o
Advanced JAVA Programming

racle");
[Link](false);

Statement stmt=[Link]();
[Link]("insert into user420 values(190,'abhi',40000");
[Link]("insert into user420 values(191,'umesh',50000");

[Link]();
[Link]
[Link]();
12/10/2023 Er. Jeewan Rai 26
}}
Advanced JAVA Programming
Chapter – 4 : Database Connectivity (4 Hrs.)

12/10/2023
Er. Jeewan Rai
The End

27

You might also like