Faculty of
Computing &
Software
Eng’g
Program:
Information
Advanced Programming
Technology
G3 IT
(Regular)
Instructor:
Addisu M. (Asst.
Prof)
2
Ch re
Java Database
Th
ap e
Connectivity
te
r
Outline
Sep 20, 2025
Overview of JDBC
JDBC Drivers
Installing and setting up JDBC
Advanced Programming
Basic JDBC Programming concepts
Statements and Prepared Statements
Connecting to a Database
Populating a database
3
Overview of JDBC
Sep 20, 2025
JDBC (Java Database Connectivity) – Java API for
accessing relational DB
provides a complete set of interfaces and classes
that allows for portable access and manipulating to a
wide range of relational DBs
possible – execute SQL statements, retrieve results,
Advanced Programming
present data in a user-friendly interface, and propagate
changes back to the DB.
used to interact with multiple data sources in a
distributed & heterogeneous environment
provides RDBMS access by allowing to embed SQL
inside code
JDBC library includes APIs for each of the tasks
commonly associated with DB usage
Making a connection to a DB 4
Overview of JDBC
Sep 20, 2025
JDBC Classes and Interfaces are in the java.sql
package
Common JDBC components are:
DriverManager - Manages loading and unloading of
DB drivers from the underlying system
Driver - handles the connections with DB server
Advanced Programming
Connection - Handles connection to a specific DB
Statement - Contains SQL statement to be passed to
DB
ResultSet - Contains the record result set from the
4. Create a Statement
SQL statement passed to the DB
SQLException - handles any errors
object
that occur in a DB
application 5. Execute a query
Steps in using JDBC 6. Process the results 5
JDBC Architecture
Sep 20, 2025
relationshipsbetween Java programs, JDBC API,
JDBC drivers, and relational DBs
Advanced Programming
Architecture of
JDBC
6
JDBC Architecture
Sep 20, 2025
Case study: Yordi is in AMiT (Main campus) and
wants to buy 2kg of Banana and 5kg of Mango
Vehicle:
from Sikela
My Sikela:
Yordi in requirement
AMiT: Mr. Seid: Vehicle: 2kg Banana
Advanced Programming
Language Result of my 3kg Mango
Talk in translator req.
Amharic! Talk in
Road Gamothoo
Yordi in AMiT: Java Application.
Sikela: Database; Banana and Mango are records in database.
Wher Mr. Seid (translator): JDBC Driver Software (eg.:
e: com.mysql.jdbc.Driver)
Road: Connection 7
JDBC Driver Types
Sep 20, 2025
What are JDBC drivers?
software component enabling application to
interact with DB
To connect with individual DBs, JDBC API requires
drivers for each DB
Advanced Programming
gives out the connection to DB and implements the
protocol for transferring the query and result
between client and DB
enable to open DB connections and to interact with
it by sending SQL or DB commands then receiving
results
are DB specific and are normally provided by the
DB vendors 8
JDBC Driver Types
Advanced Programming Sep 20, 2025
Some Popular JDBC
Drivers
Sep 20, 2025
RDBM
JDBC Driver Name
S
Driver Name : com.mysql.jdbc.Driver
MySQL DB URL format:
jdbc:mysql//hostname/databaseName
Advanced Programming
Driver Name : oracle.jdbc.driver.OracleDriver
DB URL format:
Oracle
jdbc:oracle:thin@hostname:portnumber:databaseName
Driver Name : com.ibm.db2.jdbc.net.DB2Driver
DB2 DB URL format:
jdbc:db2:hostname:portnumber/databaseName
Driver Name : com.jdbc.odbc.JdbcOdbcDriver
Access
DB URL format: jdbc:odbc:databaseName 10
JDBC Programming
Steps
Sep 20, 2025
1. Application
causes driver to be
loaded Java application
2. Application asks DriverManager
for a connection to a particular DB.
3. DriverManager DriverManager asks all loaded
gives connection drivers, and one of them responds
to the application. with a connection.
Advanced Programming
java.sql.package
java.sql.DriverManager
(JDBC library)
4. Connection
supplied by
Driver for MySQL Driver for Oracle DriverManager is
databases databases used by application
to talk JDBC through
How JDBC establishes a the driver to the
connection between your database.
code and a database
MySQL
DB 11
Primary JDBC classes
Sep 20, 2025
Java classes used for JDBC
DriverManager:
used to load the class Connection: DB
which is the driver for connection interface
a specific DB
Advanced Programming
Statement: An SQL
ResultSet: set of
statement to be
results that are
executed on the
connection returned by a query
DataSource:
interface can be
used for any object
that can be used as 12
Developing DB Applications
Sep 20, 2025
Using JDBC
JDBC API consists of classes and interfaces for
establishing connections with DBs, sending SQL
statements to DBs, processing results of the SQL
statements, and obtaining DB metadata
Four key interfaces are needed to develop any DB
application:
Advanced Programming
Driver, Connection, Statement, and ResultSet
JDBC interfaces and classes are the building blocks in
the dev’t of Java DB programs 1. Load the JDBC driver
A typical Java program takes the ff steps to access the
2. Define the Connection
DB URL
3. Establish the
Connection
4. Create a Statement
object 13
Steps in using JDBC
Sep 20, 2025
1. Loading drivers
An appropriate driver must be loaded using the
statement
Class.forName("com.mysql.jdbc.Driver");
Advanced Programming
Note: Driver
Databa com.mysql.jdbc.Driver
Class is aSource
class in mysql-
se connector-java.jar
drivers
Access for Access, MySQL, and Oracle
sun.jdbc.odbc.jdbcodbcdri are
Already in listed
JDK
ver
MySQL com.mysql.jdbc.Driver Companion
website
Oracle oracle.jdbc.driver.oracleDri Companion
ver website 14
Steps in using JDBC
Sep 20, 2025
1. Loading drivers - NetBeans
Create new project by selecting Java with
Ant Java Application from Choose
Project window Give a project name
Advanced Programming
Expand the project folder and Right-click
on Libraries under the Projects tab,
select Add JAR/Folder
Select mysql-connector-java-
8.0.12.jar and click open. Now you will
see the jar file listed under Libraries 15
Steps in using JDBC
Sep 20, 2025
2. Establishing connections
To connect to DB, use the static method
getConnection(databaseURL) in DriverManager
class:
Connection con =
DriverManager.getConnection(databaseURL);
Advanced Programming
Syntax or URL for obtaining connection:
jdbc – main protocol which takes java request and
hand over into DB environment through Data
Source Name.
odbc – sub protocol which takes DB result & gives
to java env’t 16
Steps in using JDBC
Sep 20, 2025
2. Establishing connections
lists of URLs for MySQL, Oracle, and Access
databases.
Databas URL Pattern
e
Access jdbc:odbc:DataBaseName
Advanced Programming
MySQL “jdbc:mysql://hostname:portnumber/
dbname”, “username”, “password”
Oracle jdbc:oracle:thin:@hostname:port#:oracleDBS
ID
N.B: for Mysql on my local computer:
hostname is localhost
port number is 3306 and 17
Steps in using JDBC
Sep 20, 2025
2. Establishing connections
To obtain connection from DB, as a part of jdbc we have a
predefined class java.sql.DriverManager which contains
the ff methods:
Advanced Programming
public static Connection getConnection (String
URL); //if there is no username and password DBs
public static Connection getConnection (String
URL, String username, String password); //if there
is username & password
Connection con1=DriverManager.getConnection
18
Steps in using JDBC
Sep 20, 2025
3. Creating statements
Once a Connection object is created, you can
create statements for executing SQL
statements as follows: Statement stat =
Advanced Programming
connection.createStatement();
19
Developing DB
Applications
Sep 20, 2025
4. Executing statements.
update statement can be executed using
executeUpdate(String sql)
query statement can be executed using
executeQuery(String sql)
Advanced Programming
result of the query is returned in ResultSet
E.g, create table Temp (col1 char(5), col2
stat.executeUpdate("create table Temp(col1
char(5)):
char(5), col2 char(5))");
E.g, select firstName, mi, lastName from Student
// Select the columns from the Student table
where
ResultSetlastName
resSet == ‘Hawa':
stat.executeQuery ("SELECT firstName,
mi, lastName FROM Student WHERE 20
Developing DB
Applications
Sep 20, 2025
5. Processing ResultSet
ResultSet maintains a table whose current row can
be retrieved
initial row position is null
You can use next() method to move to the next
Advanced Programming
row and the various get methods to retrieve
values from a current row
For example, code given below displays all the
// results from the
Iterate through the preceding SQLthe
result and print query
student names
while (resSet.next()){
System.out.println(resSet.getString(1) + " " +
resSet.getString(2) + ". "
+ resSet.getString(3)); 21
Statements in JDBC
Sep 20, 2025
Statement is an interface that represents a SQL
statement
Via statement objects, SQL statements are sent to the
DB
3 types of statement are available:
Statement
Advanced Programming
For executing a multiple SQL query
But, every time we execute the query, it needs to be
re-compiled
It’s the base interface for all other statements
PreparedStatement
For executing a precompiled SQL statement passing in
parameters
Every time we execute the query, it compiled once
Performance is best than Statement 22
Statements in JDBC
Sep 20, 2025
Interfaces Recommended Use
Use for general-purpose access to your
DB
Useful when you are using static SQL
Statement statements at runtime
Used to implement statements with no
Advanced Programming
parameters
Use when you plan to use statements
PreparedStatem many times
ent accepts input parameters at runtime
Used for precompiling SQL statements
that might contain input parameters
• can also accept runtime input
CallableStatem • parameters
ent Used to contain stored procedures that 23
Statement
Sep 20, 2025
Once you've created a Statement object, you can
then use it execute(String
boolean to execute a statement
SQL):
with one of its
three execute
Returns methods
a boolean value of true if a ResultSet object
can be retrieved; otherwise, it returns false
used if the execution produces multiple result sets,
multiple update counts, or a combination of result sets
Advanced Programming
int and update counts
executeUpdate(String SQL):
Returns numbers of rows affected by execution of
statement
Used to execute SQL statements for which you expect
to get a number of rows affected or update
E.g., INSERT, UPDATE, or DELETE statement
ResultSet executeQuery(String SQL):
Returns a single ResultSet object
Use this method when you expect to get a result set,
as you would with a SELECT statement 24
Statement
Sep 20, 2025
Creating Statement Object:
use Connection object's createStatement() method
con.createStatement();
Closing Statement Object:
as closing Connection object save DB resources,
Advanced Programming
for the same reason also close the Statement
object - close() method
Statement stmt = con.createStatement();
stmt.execute("INSERT
int res = INTO StInfo VALUES
(1,'Atnafu')");
stmt.executeUpdate("delete from user where UserId=3
");
System.out.println(res+" records affected");
getString(columnName) methods – retrieve 25
Statement
Sep 20, 2025
Updat Examp
eStatement stmt = con.createStatement(); le
//stmt.executeUpdate("insert into user values
(3,'Selam','256')");
Advanced Programming
//int result =
stmt.executeUpdate("update user set username =
‘Selam’, password = ‘123’ where UserId = 4");
int result=stmt.executeUpdate("delete from user w
here UserId = 3");
System.out.println(result+" records are affected"); 26
Statement
Sep 20, 2025
Retriev Examp
eString QUERY = "select * from user"; le
ResultSet rs = stmt.executeQuery(QUERY);
while (rs.next()) {
Advanced Programming
int uid = rs.getInt("UserId");
String uname = rs.getString("username");
String pwd = rs.getString("password");
System.out.println("Id: " + uid + "\n" +
"Username: " + uname + "\n" + "Password: "
+ pwd);
} 27
PreparedStatement
Sep 20, 2025
sub-interface of Statement, used to execute
parameterized query & inherits all methods
defined in Statement
Example: String sql =
"insert into user values(?,?,?)";
setString(int paramIndex, String value)
Advanced Programming
sets String value to the specified
parameter
Why use PreparedStatement?
Method Description
Improves performance: performance of the
sets X value to the given parameter index.
application will
setX(int X isbethe
faster
typebecause query(integer,
of parameter is String,
compiled only
paramIndex, once Float)
Double,
X value) paramIndex is the index of parameter in
statement
executeUpdat Used to execute query for create, insert, update, 28
PreparedStatement
Sep 20, 2025
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
Examp
( "jdbc:mysql://localhost:3306/se",“root",""); le
PreparedStatement pstmt
=con.prepareStatement(
"insert into user values(?,?,?)"); Insert
Advanced Programming
stmt.setInt(1,8);//1 specifies the first parameter
in the query
stmt.setString(2,"Selam");
stmt.setString(3,"@all");
stmt.executeUpdate();
PreparedStatement stmt =
pstmt.close(); //Closing PreparedStatement
con.prepareStatement ("update user set
Obeject Updat username = ? where UserId = ?");
stmt.setString(1,“Rutha");
e stmt.setInt(2,4); 29
PreparedStatement
Sep 20, 2025
Examp
PreparedStatement stmt = con.prepareStatement
("select * from user");
le
ResultSet rs = stmt.executeQuery(); Retriv
while(rs.next()){ e
Advanced Programming
System.out.println(rs.getInt(1) + "" +
rs.getString(2));
PreparedStatement stmt=con.prepareStat
}
ement ("delete from emp where id=?");
stmt.setInt(1,101);
Delete
int i = stmt.executeUpdate();
System.out.println(i+" records deleted"); 30
ResultSet
Sep 20, 2025
SQL statements that read data from a DB query
return the data in a result set
rows that satisfy a particular query are called
result set
executeQuery() method - used to send query to
Advanced Programming
DBMS and returns a ResultSet object that contains
data that was requested by the query
user can access the data in a result set using a
cursor one row at a time from top to bottom
maintains a cursor that points to current row in the
result set
initial row position is null
use next() method to move to the next row 31
ResultSet
Sep 20, 2025
Examp
Statement stmt = con.createStatement();
le
ResultSet rs = stmt.executeQuery("select * from
user");
Advanced Programming
// Iterate through the result and print the student
names
while (rs.next()) {
int uid = rs.getInt("UserId");
String uname = rs.getString("username");
String pwd = rs.getString("password");
System.out.println("Id: " + uid + "\n" + 32
33
THANKS
!
Questions,
Ambiguities,
Doubts, … ???