0% found this document useful (0 votes)
26 views47 pages

Week 10 OOP SQL and Javafx PDF

Uploaded by

kmamaroziqov
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
26 views47 pages

Week 10 OOP SQL and Javafx PDF

Uploaded by

kmamaroziqov
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 47

SQL Commands Guide

Djuraev Sirojiddin
November 11, 2024
Introduction to Databases and DBMS

• Database: An organized collection of data for easy access and manipulation.


• Database Management System (DBMS): Provides mechanisms for storing,
organizing, retrieving, and modifying data for multiple users.
• Relational Databases: Most popular database systems today, organized into tables
with relationships between them.
• Structured Query Language (SQL): The international standard language for
interacting with relational databases.
• Used for querying (requesting information) and data manipulation.
• Pronounced as “sequel” or as individual letters.

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

• Relational Database: Logical representation of data, accessible without concern


for physical structure.
• Data Storage in Tables: Data is organized in tables; each table represents a
specific entity (e.g., Employee).
• Table Components:
• Rows: Each row represents a single entity (e.g., one employee).
• Columns: Each column holds values for specific attributes of the entity.
• Primary Key: A unique identifier for each row (e.g., Employee ID or Social Security
Number), ensuring row uniqueness.
• Ordering: Rows can be sorted by primary key in ascending or descending order or
left unsorted.

4
Database Table Structure

Number Name Department Salary Location


23603 Jones 413 1100 New Jersey
24568 Kerwin 413 2000 New Jersey
34589 Larson 642 1800 Los Angeles
35761 Myers 611 1400 Orlando
47132 Neumann 413 9000 New Jersey
78321 Stephens 611 8500 Orlando

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

AuthorID FirstName LastName


1 Paul Deitel
2 Harvey Deitel
3 Abbey Deitel
4 Dan Quirk
5 Michael Morgano

7
Creating Authors Table in SQL

-- Create Authors Table


CREATE TABLE Authors (
AuthorID INT AUTO_INCREMENT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL
);

8
Titles Table

ISBN Title EditionNumber Copyright


0133807800 Java How to Program 10 2015
013299044X C How to Program 7 2013
0133406954 Visual Basic 2012 How to Program 6 2014
0133379337 Visual C# 2012 How to Program 5 2014
0136151574 Visual C++ 2008 How to Program 2 2008
0133378713 C++ How to Program 9 2014

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

The SELECT command retrieves data from a table.


Syntax:
SELECT column1, column2, ...
FROM table_name;

Example 1:
SELECT AuthorID, FirstName,LastName FROM Authors;

Example 2:
SELECT * FROM Authors;

Retrieves the AuthorID, First and LastName.


15
Simple result of SELECT * FROM Authors

AuthorID FirstName LastName


1 Paul Deitel
2 Harvey Deitel
3 Abbey Deitel
4 Dan Quirk
5 Michael Morgano

16
WHERE Clause in SQL

• The WHERE clause filters rows based on specified criteria.


• Used to retrieve, update, or delete rows that match the selection criteria.
• Syntax: SELECT column1, column2 FROM table WHERE condition.

Example Query: Retrieve Title, EditionNumber, and Copyright for books


published after 2013:
SELECT Title, EditionNumber, Copyright
FROM Titles
WHERE Copyright > ’2013’

17
Titles Table

Title EditionNumber Copyright


Java How to Program 10 2015
Java How to Program, Late Objects Version 10 2015
Visual Basic 2012 How to Program 6 2014
Visual C# 2012 How to Program 5 2014
C++ How to Program 9 2014
Android How to Program 2 2015

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

AuthorID FirstName LastName


1 Paul Deitel
2 Harvey Deitel
3 Abbey Deitel

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

• Qualified Names: The syntax tableName.columnName is used to distinguish


columns from different tables, especially when they have the same name.

22
Authors and ISBNs Table

FirstName LastName ISBN


Abbey Deitel 0132121360
Harvey Deitel 0133764036
Abbey Deitel 0133570924
Harvey Deitel 0133378713
Abbey Deitel 0133764036
Harvey Deitel 0136151574
Abbey Deitel 0133406954
Harvey Deitel 0133379337
Abbey Deitel 0132990601
Harvey Deitel 0133406954
Abbey Deitel 0132151006

23
INSERT Statement: Basics

The INSERT statement is used to insert a new row into a table.


Syntax:
INSERT INTO tableName (columnName1, columnName2, ..., columnNameN)
VALUES (value1, value2, ..., valueN);

• tableName: The table where the row will be inserted.


• Column List: A comma-separated list of column names.
• VALUES: A comma-separated list of values matching the specified columns.

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

AuthorID FirstName LastName


1 Paul Deitel
2 Harvey Deitel
3 Abbey Deitel
4 Dan Quirk
5 Michael Morgano
6 Sue Red

26
UPDATE Statement: Basics

The UPDATE statement modifies data in a table.


Syntax:
UPDATE tableName
SET columnName1 = value1, columnName2 = value2, ...
WHERE criteria;

• tableName: The table where rows will be updated.


• SET: Specifies a comma-separated list of column = value pairs to update.
• WHERE: Optional clause to specify criteria for rows to update. Typically used to
prevent changes to all rows.

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

AuthorID FirstName LastName


1 Paul Deitel
2 Harvey Deitel
3 Abbey Deitel
4 Dan Quirk
5 Michael Morgano
6 Sue Black

29
DELETE Statement: Basics

The DELETE statement removes rows from a table.


Syntax:
DELETE FROM tableName WHERE criteria;

• tableName: The table from which rows will be deleted.


• WHERE: Optional clause to specify criteria for rows to delete.
• Omitting the WHERE clause deletes all rows in the table.

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.

Simplified Criteria: If the AuthorID is known, use a simplified WHERE clause:


WHERE AuthorID = 6;

31
Authors Table

AuthorID FirstName LastName


1 Paul Deitel
2 Harvey Deitel
3 Abbey Deitel
4 Dan Quirk
5 Michael Morgano

32
Step-by-Step Guide

Set up the JavaFX Main Class


This class initializes the JavaFX application and displays the UI.
public class Main extends Application {
private final AuthorDAO authorDAO = new AuthorDAO();
private TableView<Author> tableView = new TableView<>();
private TextField txtFirstName = new TextField();
private TextField txtLastName = new TextField();

@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"));

TableColumn<Author, String> colFirstName = new TableColumn<>("


FirstName");
colFirstName.setCellValueFactory(new PropertyValueFactory<>("
firstName"));

TableColumn<Author, String> colLastName = new TableColumn<>("


LastName");
colLastName.setCellValueFactory(new PropertyValueFactory<>("
lastName"));

tableView.getColumns().addAll(colAuthorID, colFirstName,
colLastName); 34
// Load data
loadAuthors();

// Setup input fields and buttons


txtFirstName.setPromptText("First Name");
txtLastName.setPromptText("Last Name");

Button btnAdd = new Button("Add");


btnAdd.setOnAction(e -> addAuthor());

Button btnUpdate = new Button("Update");


btnUpdate.setOnAction(e -> updateAuthor());

Button btnDelete = new Button("Delete");


btnDelete.setOnAction(e -> deleteAuthor());

35
// Layout
HBox inputBox = new HBox(10, txtFirstName, txtLastName, btnAdd,
btnUpdate, btnDelete);
VBox vbox = new VBox(10, tableView, inputBox);

Scene scene = new Scene(vbox, 600, 400);


primaryStage.setScene(scene);
primaryStage.show();
}

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

DatabaseUtil class to manage the database connection


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseUtil {


private static final String URL = "jdbc:mysql://localhost:3306/books";
private static final String USER = "your-username";
private static final String PASSWORD = "your-password";

public static Connection getConnection() throws SQLException {


return DriverManager.getConnection(URL, USER, PASSWORD);
}
}

41
Replace "your-username" and "your-password" with your MySQL credentials.
Author Class

Create an Author class to represent the data.


public class Author {
private int authorID;
private String firstName;
private String lastName;

public Author(int authorID, String firstName, String lastName) {


this.authorID = authorID;
this.firstName = firstName;
this.lastName = lastName;
}
//Getter and Setters
}

42
AuthorDAO Class

Create an AuthorDAO class to manage database operations for the Authors


table.
public class AuthorDAO {
public List<Author> getAllAuthors() throws SQLException {
List<Author> authors = new ArrayList<>();
try (Connection conn = DatabaseUtil.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Authors")) {
while (rs.next()) {
authors.add(new Author(rs.getInt("AuthorID"), rs.getString("
FirstName"), rs.getString("LastName")));
}
}
return authors;
}
43
public void insertAuthor(String firstName, String lastName) throws
SQLException {
String query = "INSERT INTO Authors (FirstName, LastName) VALUES (?,
?)";
try (Connection conn = DatabaseUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, firstName);
pstmt.setString(2, lastName);
pstmt.executeUpdate();
}
}

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

You might also like