Chapter 3 Persistence and Databases
Chapter 3 Persistence and Databases
1
Outline
Introduction
Overview of the database connectivity
Connection, Cursor, Row Objects
Create, Read, Update and Delete (CRUD) operations
Query Results and Metadata
2
Introduction
3
Saved in
Work on
Connect
For java applications JDBC
Access
Use
4
Mostly used DBMS
We have number of databases so how java
connect to each of this databases?
5
Introduction (cont.)
Java programs interact with databases using the Java Database Connectivity (JDBC™)
API.
A JDBC driver enables Java applications to connect to a database in a particular DBMS
and allows you to manipulate that database using the JDBC API.
6
JDBC
7
Relational Databases
A relational database is a type of database that organizes data into rows and
columns, which collectively form a table where the data points are related to
each other.
A relational database is a logical representation of data that allows the data to be
accessed without consideration of its physical structure.
Primary key—a column (or group of columns) with a value that is unique for each
row.
8
9
Relational Database Overview:
10
SQL
The next several subsections discuss the SQL
queries and statements using the SQL
keywords.
11
Basic SELECT Query
A SQL query “selects” rows and columns from one or more tables in a
database.
The basic form of a SELECT query is
SELECT * FROM tableName
in which the asterisk (*) wildcard character indicates that all columns
from the tableName table should be retrieved.
To retrieve all the data in the Authors table, use
SELECT * FROM Authors
To retrieve only specific columns, replace the asterisk (*) with a comma-
separated list of the column names, e.g.,
SELECT AuthorID, LastName FROM Authors
12
13
WHERE Clause
In most cases, only rows that satisfy selection criteria are selected.
SQL uses the optional WHERE clause in a query to specify the selection criteria for
the query.
The basic form of a query with selection criteria is
SELECT columnName1, columnName2, … FROM tableName WHERE
criteria
To select the Title, EditionNumber and Copyright columns from table
Titles for which the Copyright date is greater than 2013, use the query
SELECT Title, EditionNumber, Copyright
FROM Titles
WHERE Copyright > '2013'
Strings in SQL are delimited by single (') rather than double (") quotes.
The WHERE clause criteria can contain the operators <, >, <=, >=, =, <> and
LIKE.
14
15
WHERE Clause (cont.)
Operator LIKE is used for pattern matching with wildcard characters percent (%) and
underscore (_).
A pattern that contains a percent character (%) searches for strings that have zero or
more characters at the percent character’s position in the pattern.
For example, the next query locates the rows of all the authors whose last name starts
with the letter D:
SELECT AuthorID, FirstName, LastName
FROM Authors
WHERE LastName LIKE 'D%'
16
17
WHERE Clause (cont.)
18
19
ORDER BY Clause
The rows in the result of a query can be sorted into ascending or descending order by
using the optional ORDER BY clause.
The basic form of a query with an ORDER BY clause is
SELECT columnName1, columnName2, … FROM tableName ORDER BY column
ASC
SELECT columnName1, columnName2, … FROM tableName ORDER BY column
DESC
20
ORDER BY Clause (cont.)
To obtain the list of authors in ascending order by last name (), use the query
SELECT AuthorID, FirstName, LastName
FROM Authors
ORDER BY LastName ASC
To obtain the same list of authors in descending order by last name (), use the
query
SELECT AuthorID, FirstName, LastName
FROM Authors
ORDER BY LastName DESC
Multiple columns can be used for sorting with an ORDER BY clause of the form
ORDER BY column1 sortingOrder, column2 sortingOrder, …
sortingOrder is either ASC or DESC.
Sort all the rows in ascending order by last name, then by first name.
SELECT AuthorID, FirstName, LastName
FROM Authors
ORDER BY LastName, FirstName
21
22
ORDER BY Clause (cont.)
which returns the ISBN, Title, EditionNumber and Copyright of each book
in the Titles table that has a Title ending with "How to Program" and sorts
them in ascending order by Title.
23
24
Merging Data from Multiple Tables:
INNER JOIN
Database designers often split related data into separate tables to ensure
that a database does not store data redundantly.
Often, it is necessary to merge data from multiple tables into a single
result.
Referred to as joining the tables
An INNER JOIN merges rows from two tables by matching values in
columns that are common to the tables.
SELECT columnName1, columnName2, …
FROM table1
INNER JOIN table2
ON table1.columnName = table2.columnName
The ON clause specifies the columns from each table that are compared
to determine which rows are merged—these fields almost always
correspond to the foreign-key fields in the tables being joined.
25
Merging Data from Multiple Tables:
INNER JOIN (cont.)
The following query produces a list of authors accompanied by the ISBNs for books
written by each author:
SELECT FirstName, LastName, ISBN
FROM Authors
INNER JOIN AuthorISBN
ON Authors.AuthorID = AuthorISBN.AuthorID
ORDER BY LastName, FirstName
26
INSERT Statement
indicates that values are provided for the FirstName and LastName columns. The
corresponding values are 'Sue' and ‘Red'.
We do not specify an AuthorID in this example because AuthorID is an
autoincremented column in the Authors table.
Not every database management system supports autoincremented columns.
28
UPDATE Statement
An UPDATE statement modifies data in a table.
UPDATE tableName
SET columnName1 = value1, columnName2 = value2, …,
columnNameN = valueN
WHERE criteria
where tableName is the table to update.
tableName is followed by keyword SET and a comma-separated list of
columnName = value pairs.
Optional WHERE clause provides criteria that determine which rows to
update.
The UPDATE statement-
UPDATE Authors
SET LastName = ‘Black'
WHERE LastName = ‘Red' AND FirstName = 'Sue'
indicates that LastName will be assigned the value Jones for
the row where LastName is Red and FirstName is Sue.
29
30
DELETE Statement
A SQL DELETE statement removes rows from a table.
DELETE FROM tableName WHERE criteria
31
32
How java application talk to
databases then ?
33
3.5 Overview of the database connectivity
34
JDBC Architecture
35
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Class.forName() is a static
method in Java’s
java.lang.Class class. It
dynamically loads a class into
memory at runtime by its fully
qualified name (e.g.,
com.mysql.cj.jdbc.Driver).
In the context of JDBC, it was
historically used to register a
database driver with the
DriverManager before
establishing a connection.
Database
JDBC calls commands
Driver
Database
37
Overview of Querying a Database With JDBC
Connect
Query
Process
Results
Close
38
Stage 1: Connect
Process
results
Close
39
Registering a Driver
In order to begin with, you first need to load the driver or register it before using it in the program.
Registration is to be done once in your program.
You can register a driver in one of two ways mentioned below as follows:
Class.forName()
Here we load the driver’s class file into memory at the runtime.
No need of using new or create objects. DriverManager.registerDriver()
The following example uses Class.forName() to load the Oracle DriverManager is a Java inbuilt class with a static
driver as shown below as follows: member register.
Here we call the constructor of the driver class at
Class.forName(“oracle.jdbc.driver.OracleDriver”); compile time.
Statically load driver
Class.forName(“Driver Name”);
The following example uses
Use the jdbc.drivers system property
DriverManager.registerDriver()to register the Oracle
Every driver has its own name
driver as shown below:
For example
mysql - com.mysql.jdbc.Driver
Oracle - oracle.jdbc.driver.OracleDriver DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
40
Connection to the Database
41
JDBC URLs
JDBC uses a URL to identify the database connection
jdbc:subprotocol:source
42
Connection
Also provides “metadata” -- information about the database, tables, and fields
Also methods to deal with transactions
43
Obtaining a Connection
String url = jdbc:oracle:thin:@dbserv.cs.siu.edu:1521:cs";
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url);
}
catch (ClassNotFoundException e)
{ e.printStackTrace(); }
catch (SQLException e)
{ e.printStackTrace(); }
44
Stage 2: Query
Connect
Close
45
Statement
A Statement object is used for executing a SQL statement and obtaining the results
produced by it.
Different types of Statements
Statement
PreparedStatement
CallabaleStatment
46
Statement
Statement st = con.createStatement();
Statement
Used for executing a static SQL statement
Unlike a regular Statement, which executes static SQL strings, PreparedStatement is designed
for queries or updates where values change—like user inputs or repeated operations.
48
CallableStatment
Many DBMS can store individual or set of SQL statements in a database
Stored Procedures
A stored procedure is a prepared SQL code that you can save, so the code can
be reused over and over again.
executeQuery(String)
Accepts SQL query
Execute a SQL query that returns a single ResultSet
executeUpdate(String)
50
Class Myclass
51
Stage 3: Process the Results
Connect
Query
Step through the results
Close
52
ResultSet
A ResultSet provides access to a table of data generated by executing
a Statement.
Only one ResultSet per Statement can be open at once.
The table rows are retrieved in sequence.
A ResultSet maintains a cursor pointing to its current row of data.
The 'next' method moves the cursor to the next row.
A ResultSet is an interface in the java.sql package that represents the data
returned from a database query, typically a SELECT statement.
It acts like a table of rows and columns, letting you iterate over the results
and extract values (e.g., strings, integers) from each row.
53
boolean next()
activates the next row
the first call to next() activates the first row
returns false if there are no more rows
54
ResultSet Methods
55
ResultSet Methods
• String getString(String columnName)
• boolean getBoolean(String columnName)
• byte getByte(String columnName)
• short getShort(String columnName)
• int getInt(String columnName)
• long getLong(String columnName)
• float getFloat(String columnName)
• double getDouble(String columnName)
• Date getDate(String columnName)
• Time getTime(String columnName)
• Timestamp getTimestamp(String columnName)
56
Stage 4: Close
Connect
Query
Close the result set
Process
results Close the statement
57
Close
• Close the ResultSet object
• void close()
– disposes of the ResultSet
– allows you to re-use the Statement that created it
– automatically called by most Statement methods
• void close()
Close the connection
void close()
58
Step 1: import java.sql Package
Step2: Load and register the driver
Step 3:Connect to the database
Step 4: Create statements
Step 5: Execute statements & Process the Result
Step 6: close ResultSet and Statement
Step 7: Close the connection
59
JDBC Object Classes
• DriverManager
– Loads, chooses drivers
• Driver
– connects to actual database
• Connection
– a series of SQL statements to and from the DB
• Statement
– a single SQL statement
• ResultSet
– the records returned from a Statement
The following program demonstrates how to connect to a MySQL database using JDBC, execute a query,
retrieve the results, and display them in a Java program.
60
Overview of what the code does
1.The program loads the MySQL JDBC driver using the
Class.forName() method.
2.It then connects to the MySQL database using the
DriverManager.getConnection() method and a JDBC URL that
specifies the database name, username, and password.
3.It creates a Statement object to execute SQL queries.
4.It executes a SELECT query on the "Authors" table using the
executeQuery() method and stores the results in a ResultSet object.
5.It iterates through the ResultSet using the next() method and
retrieves the values of the "authorId", "firstName", and "lastName"
columns using the getInt() and getString() methods.
6.It displays the retrieved data using the System.out.println()
method.
7.It closes the ResultSet, Statement, and Connection objects using
61
} catch (Exception e) {
e.printStackTrace();
} }}
63
Overview of what the code does
1.The program loads the MySQL JDBC driver using the Class.forName()
method.
2.It then connects to the MySQL database using the
DriverManager.getConnection() method and a JDBC URL that specifies
the database name, username, and password.
3.It creates a PreparedStatement object to execute SQL statements. In
this case, the SQL statement is an INSERT statement that inserts a new
record into the "Authors" table with a first name of "John" and a last name
of "Doe". The ? placeholders are used to specify parameter values later.
4.It sets the parameter values for the INSERT statement using the
setString() method.
5.It executes the INSERT statement using the executeUpdate() method
and gets the number of rows affected.
6.It displays a message indicating how many rows were inserted.
7.It closes the PreparedStatement and Connection objects using the
close() method. 64
Insert a single record
import java.sql.*;
public class InsertAuthor {
public static void main(String[] args) {
try { // Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to the database String url =
"jdbc:mysql://localhost:3306/Books?user=myuser&password=
mypassword"; Connection conn =
DriverManager.getConnection(url); // Create a
PreparedStatement object to execute SQL statements
String query = "INSERT INTO Authors (firstName, lastName)
VALUES (?, ?)";
65
PreparedStatement pstmt = conn.prepareStatement(query);
Insert a single record
// Set the parameter values for the query
pstmt.setString(1, "John");
pstmt.setString(2, "Doe");
// Execute the query and get the number of rows affected
int rows = pstmt.executeUpdate();
System.out.println(rows + " row(s) inserted.");
// Close the PreparedStatement and Connection objects pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
66
}}}
Overview of what the update code does
1.The program loads the MySQL JDBC driver using the Class.forName()
method.
2.It then connects to the MySQL using DriverManager.getConnection()
method and a JDBC URL that specifies the database name, username, and
password.
3.It creates a PreparedStatement object to execute SQL statements. In
this case, the SQL statement is an UPDATE statement that updates the
"firstName" and "lastName" columns of the record with an "authorId" of 1
to "Jane" and "Doe", respectively. The ? placeholders are used to specify
parameter values later.
4.It sets the parameter values for the UPDATE statement using the
setString() and setInt() methods.
5.It executes the UPDATE statement using the executeUpdate() method
and gets the number of rows affected.
6.It displays a message indicating how many rows were updated.
7.It closes the PreparedStatement and Connection objects using the
close() method. 67
Update a single record
import java.sql.*;
public class UpdateAuthor {
public static void main(String[] args) {
try { // Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to the database String url =
"jdbc:mysql://localhost:3306/Books?user=myuser&password=mypas
sword";
Connection conn = DriverManager.getConnection(url);
// Create a PreparedStatement object to execute SQL statements
String query = "UPDATE Authors SET firstName = ?, lastName = ?
WHERE authorId = ?";
PreparedStatement pstmt = conn.prepareStatement(query);
68
Update a single record
// Set the parameter values for the query
pstmt.setString(1, "Jane");
pstmt.setString(2, "Doe");
pstmt.setInt(3, 1);
// Execute the query and get the number of rows affected
int rows = pstmt.executeUpdate();
System.out.println(rows + " row(s) updated.");
// Close the PreparedStatement and Connection objects pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}}} 69
Exercises
70