Advanced Programming - Chapter 2
Advanced Programming - Chapter 2
√ JDBC defines how a client may access any kind of tabular data,
especially a relational database.
√ It acts as a middle-layer interface between Java applications and
databases.
⧫ Interacting with a database requires efficient database connectivity,
which can be achieved using the ODBC (Open database
connectivity) driver.
JDBC Product
⧫ JDBC consists of two basic components:
1. JDBC API
1. JDBC API.
●2.Provides a set of
JDBC Driver: interfaces and classes to
interact with the database
2. JDBC Driver:
● software component that enables Java
applications to connect with the database in
a particular DBMS and allow you to retrieve
and manipulate database data.
⧫ It is a database-independent driver.
ii. Application Tier: The business logic layer, which processes user
requests, performs computations, and makes decisions. It acts as
a mediator between the presentation and data tiers.
iii. Data Tier: The storage layer, is responsible for managing and
storing data. It handles database operations and data retrieval.
⧫ JDBC connects the front end (for interacting with users) with the
back end, which stores data entered by users in the table details.
Database Connection
➢How do you establish a Database Connection with Java?
⧫ Below are the steps that explain how to connect to a Database in
Java:
Step 1 – Import the Packages
Connection con;
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb" , "root" , " ") ;
Statement stmt = con.createStatement( ) ;
Connection con;
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb" , "root" , " ") ;
String sql = "insert into Student values( '001' , 'Aster Awoke' )" ;
stmt.executeUpdate(sql) ;
con.close( ) ;
Example JDBC Drivers … cont'd
➢ How do you insert batch records into a Database?
Connection con;
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb" , "root" , " ") ;
Statement stmt = con.createStatement( ) ;
String sql1 = "insert into Student values( '001' , 'Robel Tewabe' )" ;
String sql2 = "insert into Student values( '002' , 'Hayat Seid' )" ;
String sql3 = "insert into Student values( '003' , 'Dawit Desale' )" ;
stmt.addBatch(sql1) ;
stmt.addBatch(sql2) ;
stmt.addBatch(sql3) ;
stmt.executeBatch( ) ;
System.out.println("All records inserted successfully") ;
con.close( ) ;
Example JDBC Drivers … cont'd
➢ How do you fetch/retrieve records from a Database with JDBC?
Connection con;
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb" , "root" , " ") ;
Statement stmt = con.createStatement( ) ;
con.close( ) ;
Example JDBC Drivers … cont'd
Connection con;
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb" , "root" , " ") ;
Statement stmt = con.createStatement( ) ;
String sql="update Student set FirstName = ' Nardos Gashaw'
where ID=2" ;
stmt.executeUpdate(sql) ;
System.out.println("Data updated successfully") ;
con.close( ) ;