A database is an organized collection of structured information, or data, typically stored electronically in a computer system.
Multiple database types:
Examples:
jdbc:mysql://server:port/dbname?characterEncoding=UTF-8jdbc:postgresql://host:port/databaseSQLite Database JDBC URI for specific modes:
jdbc:sqlite::memory:?foreign_keys=truejdbc:sqlite:~/file/path/database.db?PROP=valueTypes:
SELECTINSERT, UPDATE, DELETECREATE, ALTER, DROPGRANT, DENY (access)-- 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 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")
);
UNIQUE, NOT NULL, immutable)"id" INTEGER PRIMARY KEY AUTOINCREMENTAre used for collections or compositions:
FOREIGN KEY is a field (or collection of fields) in one table,
that refers to the PRIMARY KEY of another table.
"departmentId" INTEGER REFERENCES "Department"("id")FOREIGN KEY ("departmentId") REFERENCES "Department"("id")PRAGMA foreign_keys = ON; in every connection!Constraints:
UNIQUE - column values must be unique"number" TEXT NOT NULL UNIQUEIndex is automatically created for:
DELETE a department with employees?ON DELETE CASCADE:
"departmentId" INTEGER REFERENCES "Department"("id") ON DELETE CASCADEsqlite_schema
-- List all user-defined tables and views
SELECT type, name, tbl_name, sql
FROM sqlite_schema
WHERE type IN ('table', 'view')
AND name NOT LIKE 'sqlite_%';


con.setAutoCommit(false)con.commit() / con.rollback() is requiredStatement!!!PreparedStatement protects against SQL InjectionPreparedStatement)// 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");
}
}
}