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

Advanced Programming - Chapter 2

Chapter Two covers database programming with Java, focusing on JDBC (Java Database Connectivity) and its components, including types of drivers and client/server models. It explains how to establish database connections, execute SQL statements, and manage data using JDBC, along with applications of Java database programming in various systems. Additionally, it discusses the Database Metadata Interface for extracting information about the database and its capabilities.

Uploaded by

Yirga Gizachew
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Advanced Programming - Chapter 2

Chapter Two covers database programming with Java, focusing on JDBC (Java Database Connectivity) and its components, including types of drivers and client/server models. It explains how to establish database connections, execute SQL statements, and manage data using JDBC, along with applications of Java database programming in various systems. Additionally, it discusses the Database Metadata Interface for extracting information about the database and its capabilities.

Uploaded by

Yirga Gizachew
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

CHAPTER TWO: Database Programming

➢In this chapter, you will learn :


● JDBC Product ● Batch Update
● Types of Drivers ● The Result Set Object Interface.
● Two-Tier Client/Server Model ● Working with Database
● Three-Tier Client/Server Model
Metadata Interface.
● Database Connection from Java
● DB Connection Class
● Database Access
● Basic Steps of JDBC
● Creating and Executing SQL Statement
Overview of Database
➢What is a Database?
⧫ A database is an organized collection of data that is stored and
accessed electronically, allowing for efficient management,
retrieval, and manipulation.

⧫ There are many different strategies for organizing data to


facilitate easy access and manipulation.

⧫ DBMS provides mechanisms for storing, organizing, retrieving,


and modifying data.

⧫ Today’s most popular database systems are relational databases.


Overview of Database
➢RDBMS
⧫ Some popular relational database management systems
(RDBMSs) include Microsoft SQL Server, Oracle, Sybase, IBM
DB2, Informix, PostgreSQL and MySQL.
⧫ For example, SQL (Structured Query Language) is used to
communicate with and manipulate relational databases.
It enables users to perform tasks such as querying data, updating
records, and managing database structure.

⧫ The JDK now comes with a pure-Java RDBMS called Java


DB—Oracles’s version of Apache Derby.
Database Programming
➢ What is Database Programming with Java?
⧫ It refers to writing Java code to connect to databases, execute
queries, retrieve and manipulate data, and manage transactions.
⧫ Java provides robust support for database operations through the
Java Database Connectivity (JDBC) API and other frameworks.

➢ Why Use Java for Database Programming?


● Platform independence and robustness.
● Wide support for database systems.
● Abundance of libraries and frameworks.
● Scalable for both small applications and enterprise-level
systems.
Database Programming
➢ Applications of Java Database Programming:
● Web applications to manage user data.
● Enterprise systems with complex transactional requirements.
● Data analytics pipelines using relational or NoSQL databases.
e.g., the Real-world Applications of DB Programming include:
√ E-commerce systems to manage product catalogs and transactions.
√ Social media platforms for user profiles and interaction data.
√ Banking systems for financial records and transaction history.

⧫ By leveraging JDBC and related frameworks, Java allows


developers to build reliable, scalable, and efficient database-
powered applications.
JDBC Product
➢What is a JDBC product?
⧫ JDBC: Java Database Connectivity.
⧫ It is a Java-based API provided by Oracle Corporation that allows
applications to interact with relational databases by providing
methods to connect, query, and update data.

√ 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.

⧫ The Java Package java.sql and javax.sql


contains classes and interfaces for accessing
relational databases in Java.
JDBC Drivers
➢Types of JDBC drivers:
⧫ JDBC drivers is a client-side adapter (installed on the client
machine, not on the server) that enables Java applications to
connect to a database in a particular DBMS and allows you to
manipulate that database using the JDBC API.
⧫ Most popular database management systems now provide JDBC
drivers.
⧫ Generally, there are four types of JDBC drivers available:
● Type-1: JDBC-ODBC bridge driver
● Type-2: Native-API driver or Partly-Java driver
● Type-3: Network Protocol driver or All-Java driver
● Type-4: Thin driver or Pure Java driver
JDBC Drivers
➢Types of JDBC drivers:
⧫ There are four types of JDBC drivers :
● Type-1: JDBC-ODBC bridge driver
● Type-2: Native-API driver
● Type-3: Network Protocol driver
● Type-4: Thin driver
1. JDBC-ODBC bridge driver – Type 1 driver
√ It uses an ODBC driver to connect to the database.
√ This driver translates JDBC method calls into the ODBC
function calls.
√ Also called Universal driver because it can be used to connect
to any of the databases.
JDBC Drivers
1. JDBC-ODBC bridge driver – Type 1 driver
⧫ It makes use of the sun.jdbc.odbc package which includes a
native library to access ODBC characteristics.

⧫ It is built-in with JDK, so no need to install it separately.

⧫ It is a database-independent driver.

⧫ As a common driver is used to interact with different databases,


the data transferred through this driver is not so secure.

⧫ This driver needs to be installed in individual client machines.


JDBC Drivers
2. Native-API driver - Type-2
⧫ The Native API driver uses the client-side libraries of the
database.
⧫ This driver translates JDBC method calls into native calls of the
database API.
⧫ Data transfer is much more secure as compared to type-1 driver.
⧫ This driver needs to be installed separately in individual client
machines
⧫ It is a database dependent driver.
⧫ This driver gives better performance than the JDBC-ODBC
bridge driver.
JDBC Drivers
3. Network Protocol driver - Type-3
⧫ This driver is used when the user has multiple databases and wants
to use a single driver to connect all of them.
⧫ Uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol.
⧫ Here all the database connectivity drivers are present in a single
server, hence no need for individual client-side installation.
⧫ Gives better performance than Type-1 and Type-2 drivers.
4. Thin driver - Type-4
⧫ Pure Java drivers that directly convert JDBC calls to database-
specific protocol calls. Most commonly used today for portability.
⧫ Does not require any native library and Middleware server, so no
client-side or server-side installation.
Types of JDBC Architecture
➢ Types of JDBC Architecture (2-Tier and 3-Tier):
⧫ The JDBC architecture consists of 2-tier and 3-tier processing
models that can be used to access a database.

1. Two-Tier Client/Server Model:


⧫ When building a system that uses a database, the architecture you
choose is key to how everything works together.
⧫ In database programming, the Two-Tier Model is a client-
server architecture in which a client application communicates
directly with a database server.
⧫ In a Two-Tier setup, you have the user interface on one side and
the database on the other with the two communicating directly.
Types of JDBC Architecture …cont'd
1. Two-tier architecture consists of two layers :
⧫ Tier 1: client Tier
● The client is the front-end application that interacts with the end user.
● The client sends SQL queries directly to the database and processes the
results returned by the server. For example, a desktop application
connecting directly to a database is a two-tier application.

⧫ Tier 2: Database Server (Data Tier)


● This is the back-end system that manages the database, handles the
queries, maintains data integrity and database storage.
● It processes requests from the client, executes database operations, and
sends results back.
● Two-tier model can be used when small applications with a limited
number of users, such as departmental or personal systems.
Types of JDBC Architecture …cont'd
2. Three-tier client/Server Architecture
⧫ The Three-Tier Client/Server Model is a software architecture
pattern that separates an application into three interconnected
layers or tiers, each with a specific responsibility.

⧫ The Three-tier architecture consists of:


● Client Tier (Presentation Tier)
● Application Tier (Middle Tier )
● Data Tier (Database Server)
⧫ In this architecture, a middle tier is added between the users'
system interface (client environment) and the database
management server environment.
JDBC Drivers
➢The Three-tier architecture :
i. Presentation Tier: The user interface layer, where interactions
occur. It handles data display and user input.

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.

⧫ This separation helps improve scalability, manageability, and


flexibility by isolating each layer’s responsibilities.
Types of JDBC Architecture …cont'd
2. Three-tier client/Server Model
⧫ In this model, 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.
Three-Tier Client/Server Architecture
in Distributed System
Database Connection
➢Database Connection from Java
⧫ Establishing a database connection in Java involves using the Java
Database Connectivity (JDBC) API, which allows Java
applications to interact with a wide range of databases

⧫ 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

Step 2 – Load the drivers using the forName( ) method

Step 3 – Register the drivers using DriverManager

Step 4 – Establish a connection using the Connection class Object

Step 5 – Create a statement

Step 6 – Execute the query

Step 7 – Close the connections


Database Connection
➢Database Connection Class:
⧫ In Java, a Database Connection Class is a user-defined class that
handles all database connectivity operations.

⧫ A typical Database Connection Class includes:


• Database URL: JDBC connection string.
• Credentials: Username and password for database access.
• Connection Logic: Method to establish and return a database
connection.
• Error Handling: Logic to handle and log connection errors.
• Closing Resources: Ensures proper closure of Connection,
Statement, and ResultSet.
Database Connection
➢Database Connection Class:
⧫ To establish a database connection with Java, use the DriverManager
class. Syntax:
Connection con = DriverManager.getConnection(
" jdbc:mysql://localhost:3306/mydatabase", "username", "password");
if (con != null) {
System.out.println("Connection successful!"); }
Here • jdbc:mysql : Protocol and driver name.
• localhost:3306: Hostname where the database server is running
and port (virtual point)
• mydatabase: Database name

● A Connection object manages the connection between a Java


program and a database. It enables programs to create SQL statements
that access data.
Database Access
⧫ In Java, Database access refers to interacting with a database to
perform operations such as querying, updating, and managing data
using the JDBC API.
⧫ The Basic Steps to connect a Java application to a Database:
● Load the database driver: Ensure the database driver is available.
● Establish a connection: Use DriverManager to connect to the database.
● Create a Statement: Use a Statement, PreparedStatement, or
CallableStatement to execute SQL queries.
● Execute queries or updates.
● Process results: Use a ResultSet to handle data retrieve
● Close the connection: Always close ResultSet, Statement, and
Connection to release resources.
Database Access
➢Creating and Executing SQL Statement:
⧫ With JDBC, SQL statements are commands written in SQL (e.g.,
SELECT, INSERT, UPDATE, DELETE) that are executed to
interact with the database.
⧫ The Statement interface in JDBC is used to create SQL
statements in Java and execute queries with the database.
⧫ Types of statements with JDBC include:
● Statement: For simple SQL queries
● PreparedStatement: For parameterized and precompiled SQL
queries.
● CallableStatement: For calling stored procedures.
Database Access
➢Types of Statements with JDBC:
1. Create Statement:
● The createStatement( ) method is used to create the Statement
object.
Syntax: Statement statement = connection.createStatement( ) ;
2. PreparedStatement
● A PreparedStatement in JDBC is a precompiled SQL statement
that allows you to execute parameterized queries efficiently.
Syntax: PreparedStatement pstmt = con.prepareStatement(parm);
Example:
String query = "INSERT INTO people(name, age)VALUES(?, ?)" ;
PreparedStatement pstmt = con.prepareStatement(query) ;
Database Access
➢Types of Statements with JDBC:
3. CallableStatement:
● A CallableStatement is an interface in Java that is used to execute
stored procedures in the database.
● Stored procedures are precompiled SQL statements that can be
called with parameters to execute complex operations that involve
multiple SQL statements.
Syntax: To create a CallableStatement
CallableStatement cstmt = con.prepareCall("{call ProcedureName( ?, ? ) }") ;

● {call ProcedureName(?, ?)}:


√ Calls a stored procedure named ProcedureName with
placeholders ' ? ' for input parameters.
Database Access
➢Batch Update with Java:
⧫ In Java, Batch Update is a technique used to execute multiple
database update operations (e.g., INSERT, UPDATE, or
DELETE) as a single batch.
⧫ Instead of sending individual SQL statements to the database, you
group multiple operations and send them together
⧫ JDBC provides a way to execute multiple SQL statements as a
batch using addBatch( ) and executeBatch( ) methods.
✓ This is efficient for operations like inserting multiple rows or
updating multiple records.
✓ For example, INSERT, UPDATE, DELETE) in a single
request, which improves performance by reducing the number
of database calls.
Database Access
➢ResultSet Obect with Java:
● A ResultSet object represents the data retrieved from a database
query using JDBC. It acts as a cursor pointing to the rows of the
result set returned by a SQL query.
● The ResultSet is essentially a table of data where each row
represents a record, and each column represents a field in the
database
● It is created when you execute a query using a Statement or
PreparedStatement object.
● For example:
CallableStatement cstmt = con.prepareCall("{call ProcedureName( ?, ? ) }") ;
Database Metadata Interface

➢Working with Database MetaData Interface:


⧫ In JDBC, you have one interface for extracting metadata from the
database: Database Metadata.

⧫ The Database MetaData Interface is an API that provides


information about the database and its capabilities.

✓ It provides methods to retrieve metadata information about the


database such as database name, driver version, tables, columns,
keys, user roles, and supported SQL features.
Database Metadata Interface
➢Database MetaData Interface:
⧫ By using the DatabaseMetaData class, we can perform different
tasks such as:
√ Retrieving information about database products like database
name, driver version, columns, keys, and supported SQL
features.
⧫ Some methods with JDBC:
● SQLGetInfo( ): retrieves information about supported SQL features.
● getTables( ): Retrieves information about tables, views, indexes, and
keys.
● getColumns( ): Retrieves details about the columns of a table,
including data types, nullability, default values, etc.
Database Metadata Interface
➢How to extract Database Metadata with JDBC?
⧫ To extract Database Metadata, first you must connect the database
by using some database configuration properties such as localhost
name, database name, username, password, database port number,
and other properties.
⧫ Then, you need to create an object for the DatabaseMetadata class,
and you must assign the result of con.getMetadata( ).

⧫ Then, by using that object, you can extract the database


information.
⧫ Database Metadata interfaces help developers analyze and interact
with databases dynamically and efficiently.
Database Metadata Interface
Example: The following statements extract the database product
name and version.
DatabaseMetaData metaData = connection.getMetaData( ) ;
System.out.println("Database Product Name: " +
metaData.getDatabaseProductName( )) ;
System.out.println("Database Version: " +
metaData.getDatabaseProductVersion( )) ;

⧫ Database MetaData Interface allows you to extract database


information such as:
√ Database name and vendor, √ User and Privileges Information,
√ Driver information,
√ Database access path
√ Table and schema details,
√ Other supported SQL features
Database Metadata with JDBC
// This example demonstrates the Database Metadata Interface
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

public class RetrieveDataExample {


public static void main(String[] args) {
try {
// load MySQL JDBC driver class
Class.forName("com.mysql.cj.jdbc.Driver") ;
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/books", "root", "password") ;
Database Metadata with JDBC … cont'd

// Retrieve metadata about the database


DatabaseMetaData metaData = con.getMetaData( ) ;
// Print the name of the database product
System.out.println("\n\t Database Product Name: " +
metaData.getDatabaseProductName( )) ;
// Print the version of the database product
System.out.println("\n\tDatabase Product Version: " +
metaData.getDatabaseProductVersion( )) ;

// Print the name of the JDBC driver being used


System.out.println("Driver Name: " + metaData.getDriverName( ));

// Print the version of the JDBC driver being used


System.out.println("Driver Version: " + metaData.getDriverVersion( )) ;
Database Metadata with JDBC … cont'd
// Print the username of the current user accessing the database
System.out.println("Database UserName : " + metaData.getUserName( ));
// Print the URL of the database connection
System.out.println("Database URL Information : " + metaData.getURL( ));
// Close the database connection
con.close( ) ;
} catch (ClassNotFoundException | SQLException e)
{
// handle exceptions that will occur during the process
System.out.println("Exception is " + e.getMessage( )) ;
}
}
}
Example JDBC Drivers
➢ How do you create a table with a JDBC?

Connection con;
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb" , "root" , " ") ;
Statement stmt = con.createStatement( ) ;

String sql = "create Table Student( ID int ,


Name varchar(15) not null , primary key(ID))" ;
stmt.executeUpdate(sql) ;

System.out.println(" Table created successfully") ;


con.close( ) ;
Example JDBC Drivers … cont'd
➢ How do you insert a record to a Database with JDBC?

Connection con;
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb" , "root" , " ") ;

Statement stmt = con.createStatement( ) ;

String sql = "insert into Student values( '001' , 'Aster Awoke' )" ;
stmt.executeUpdate(sql) ;

System.out.println("A record inserted successfully") ;

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( ) ;

String query = "select * from student" ;


ResultSet rs = stmt.executeQuery(query) ;
while(rs.next( ) )
{
System.out.println(rs.getInt(
"ID") + "\t" rs.getString("FirstName") ) ;
}

con.close( ) ;
Example JDBC Drivers … cont'd

➢ How do you update inserted data from a Database with JDBC?

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( ) ;

You might also like