PV168

Databases


What is a Database

A database is an organized collection of structured information, or data, typically stored electronically in a computer system.

Multiple database types:


JDBC – Java Database Connectivity


JDBC URI

Examples:

SQLite Database JDBC URI for specific modes:


SQL - Structured Query Language

Types:


Create a new Department Table

-- create a new Department table
CREATE TABLE IF NOT EXISTS "Department"
(
    "id"        INTEGER PRIMARY KEY AUTOINCREMENT,
    "number"    TEXT NOT NULL UNIQUE,
    "name"      TEXT NOT NULL,
    "createdAt" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

Create a new Employee Table

-- create a new Emplotee table
CREATE TABLE IF NOT EXISTS "Employee"
(
    "id"           INTEGER PRIMARY KEY AUTOINCREMENT,
    "number"       TEXT NOT NULL UNIQUE,
    "firstName"    TEXT NOT NULL,
    "lastName"     TEXT NOT NULL,
    "birthDate"    TEXT NOT NULL,
    "departmentId" INTEGER,
    "createdAt"    TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY ("departmentId") REFERENCES "Department"("id")
);

Primary Key


Relationships

Are used for collections or compositions:


Foreign Key

FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY of another table.


Constraints and Default Indexes

Constraints:

Index is automatically created for:


Cascades


Information Schema


Migrations


JDBC: Architecture

bg 50%


JDBC API

bg 50%


JDBC Connection


JDBC (Prepared) Statement


JDBC ResultSet


Code Sample

// connection and statement should be both closed after we are done
try(
    Connection connection = dataSource.getConnection();
    var statement = connection.prepareStatement("SELECT id, number FROM Department WHERE id = ?")
) {
    ps.setLong(1, departmentID); // set the
    try (var rs = statement.executeQuery()) { // we should close the result set
        while (rs.next()) {
            long departmentId = rs.getLong("id");
            String number = rs.getString("number");
        }
    }
}