Week 10 OOP SQL and Javafx PDF
Week 10 OOP SQL and Javafx PDF
Djuraev Sirojiddin
November 11, 2024
Introduction to Databases and DBMS
2
Popular RDBMS and Java Database Interaction
• Popular RDBMS: Microsoft SQL Server, Oracle, IBM DB2, PostgreSQL, MySQL,
Java DB (Apache Derby).
• Java Database Connectivity (JDBC):
• API for Java programs to connect to and manipulate databases.
• JDBC drivers available for popular DBMS.
• Java Persistence API (JPA):
• Automatically generates Java classes to represent database tables and relationships.
• Enables object-relational mapping, hiding database interaction details from developers.
3
Relational Databases and Tables
4
Database Table Structure
5
A "books" Database
• Purpose: The database is used to illustrate SQL and database concepts, including
data retrieval and manipulation.
• Database Creation: A script is provided to create the database;
• Database Tables:
• Authors: Stores each author’s unique ID, first name, and last name.
• AuthorISBN: Links authors to book titles.
• Titles: Contains details about each book title.
6
Authors Table
7
Creating Authors Table in SQL
8
Titles Table
9
CREATE TABLE Titles (
ISBN CHAR(13) PRIMARY KEY,
Title VARCHAR(255) NOT NULL,
EditionNumber INT NOT NULL,
Copyright YEAR NOT NULL
);
10
AuthorISBN Table
AuthorID ISBN
1 0132151006
2 0133379337
2 0132151006
1 0136151574
3 0132151006
2 0136151574
1 0133807800
4 0136151574
2 0133807800
11
-- Create AuthorISBN Table for Many-to-Many Relationship
CREATE TABLE AuthorISBN (
AuthorID INT,
ISBN CHAR(13),
FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID) ON DELETE CASCADE ON
UPDATE CASCADE,
FOREIGN KEY (ISBN) REFERENCES Titles(ISBN) ON DELETE CASCADE ON UPDATE
CASCADE,
PRIMARY KEY (AuthorID, ISBN)
);
12
Introduction to SQL for Books Database
The table below lists some essential SQL keywords and their descriptions. These
commands enable data retrieval, manipulation, and management within the database.
14
2. SELECT Statement
Example 1:
SELECT AuthorID, FirstName,LastName FROM Authors;
Example 2:
SELECT * FROM Authors;
16
WHERE Clause in SQL
17
Titles Table
18
Using the Percent (%) Wildcard in SQL
• The % wildcard in SQL matches zero or more characters at its position in the
pattern.
• Used with the LIKE operator to perform pattern matching in string searches.
• Example: Find authors with last names starting with "D".
Example Query:
SELECT AuthorID, FirstName, LastName
FROM Authors
WHERE LastName LIKE ’D%’
Explanation:
• This query retrieves AuthorID, FirstName, and LastName for authors whose
LastName begins with "D".
19
Authors Table
20
Merging Data from Multiple Tables: INNER JOIN
• Data Normalization: Database designers often separate related data into different
tables to prevent redundancy. For example, in the books database, the
AuthorISBN table links authors to their titles without duplicating author
information in the Titles table.
• INNER JOIN: Used to merge rows from two tables by matching values in common
columns. This operation creates a single result set that includes data from both
tables.
• ON Clause: Specifies the columns from each table to compare for merging, typically
foreign-key fields. The basic structure:
SELECT columnName1, columnName2, ...
FROM table1
INNER JOIN table2
ON table1.columnName = table2.columnName
21
• Example Query: Retrieves authors and their book ISBNs, sorted by LastName and
FirstName.
SELECT FirstName, LastName, ISBN
FROM Authors
INNER JOIN AuthorISBN
ON Authors.AuthorID = AuthorISBN.AuthorID
ORDER BY LastName, FirstName
22
Authors and ISBNs Table
23
INSERT Statement: Basics
Note: Explicitly list columns when inserting rows to avoid errors if table structure
changes.
24
INSERT Statement: Example with Authors Table
When adding a new row to the Authors table, specify values for FirstName and
LastName. The AuthorID column is auto-incremented.
Example:
INSERT INTO Authors (FirstName, LastName)
VALUES (’Sue’, ’Red’);
• This INSERT statement adds a new author with FirstName = ’Sue’ and
LastName = ’Red’.
• The AuthorID is automatically assigned by the DBMS as it’s an auto-incremented
column.
Note: Not all DBMSs support auto-increment. Check your DBMS documentation for
alternatives.
25
Authors Table
26
UPDATE Statement: Basics
Note: Omitting the WHERE clause will update all rows in the table.
27
UPDATE Statement: Example with Authors Table
The following example changes the LastName of a specific author in the Authors
table.
Example:
UPDATE Authors
SET LastName = ’Black’
WHERE LastName = ’Red’ AND FirstName = ’Sue’;
• This UPDATE statement sets LastName to ’Black’ for the row where
LastName = ’Red’ and FirstName = ’Sue’.
• If multiple rows match the criteria, all will be updated to have LastName =
’Black’.
Simplified Criteria: If the AuthorID is known, use a simplified WHERE clause:
28
WHERE AuthorID = 6;
Authors Table
29
DELETE Statement: Basics
30
DELETE Statement: Example with Authors Table
The following example deletes a specific author from the Authors table.
Example:
DELETE FROM Authors
WHERE LastName = ’Black’ AND FirstName = ’Sue’;
• This DELETE statement removes the row where LastName = ’Black’ and
FirstName = ’Sue’.
• If multiple rows match the criteria, all of them will be deleted.
31
Authors Table
32
Step-by-Step Guide
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Authors Database");
33
// Setup columns
TableColumn<Author, Integer> colAuthorID = new TableColumn<>("
AuthorID");
colAuthorID.setCellValueFactory(new PropertyValueFactory<>("
authorID"));
tableView.getColumns().addAll(colAuthorID, colFirstName,
colLastName); 34
// Load data
loadAuthors();
35
// Layout
HBox inputBox = new HBox(10, txtFirstName, txtLastName, btnAdd,
btnUpdate, btnDelete);
VBox vbox = new VBox(10, tableView, inputBox);
36
private void loadAuthors() {
try {
tableView.getItems().setAll(authorDAO.getAllAuthors());
} catch (Exception e) {
e.printStackTrace();
}
}
37
private void addAuthor() {
try {
authorDAO.insertAuthor(txtFirstName.getText(), txtLastName.
getText());
loadAuthors();
txtFirstName.clear();
txtLastName.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
38
private void updateAuthor() {
Author selected = tableView.getSelectionModel().getSelectedItem();
if (selected != null) {
try {
authorDAO.updateAuthor(selected.getAuthorID(), txtFirstName.
getText(), txtLastName.getText());
loadAuthors();
} catch (Exception e) {
e.printStackTrace();
}
}
}
39
private void deleteAuthor() {
Author selected = tableView.getSelectionModel().getSelectedItem();
if (selected != null) {
try {
authorDAO.deleteAuthor(selected.getAuthorID());
loadAuthors();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
40
Database Connection Utility
41
Replace "your-username" and "your-password" with your MySQL credentials.
Author Class
42
AuthorDAO Class
44
public void updateAuthor(int authorID, String firstName, String
lastName) throws SQLException {
String query = "UPDATE Authors SET FirstName = ?, LastName = ?
WHERE AuthorID = ?";
try (Connection conn = DatabaseUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, firstName);
pstmt.setString(2, lastName);
pstmt.setInt(3, authorID);
pstmt.executeUpdate();
}
}
45
public void deleteAuthor(int authorID) throws SQLException {
String query = "DELETE FROM Authors WHERE AuthorID = ?";
try (Connection conn = DatabaseUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setInt(1, authorID);
pstmt.executeUpdate();
}
}
}
46
Explanation of Key Components
• Main Application (Main class): Creates the JavaFX UI components and handles
user interactions such as adding, updating, and deleting authors.
• Database Connection (DatabaseUtil class): Manages the connection to the
MySQL database, enabling CRUD operations.
• Data Model (Author class): Represents an author with authorID, firstName, and
lastName attributes.
• Data Access Object (AuthorDAO class): Provides methods to perform SQL
operations (SELECT, INSERT, UPDATE, DELETE) on the Authors table.
47