Java tutorialLesson 14 of 18 · tap to see all lessons
Java tutorial · Beginner
Database Basics for Java Developers: Tables, Keys, MySQL Data Types, and Workbench
Learn why applications store data in a database, how tables, rows, and columns work, which MySQL data types to choose, and how primary and foreign keys link tables.
- Qyubie Learn Editorial Team
- Published
- 12 min read
Includes 1 exercise and 3 quick checks you can do right here.
Every object you created in the last lessons disappeared the moment the program ended. Run the enrollment program again and the students are gone. Real applications keep their data in a database, so it survives restarts and many users can share it. The next three lessons cover databases and SQL; after that, in lesson 19, your Java programs will connect to them.
By the end of this lesson you will be able to:
- explain what a database and a DBMS are, and why applications use them,
- describe tables, rows, and columns, and relate them to classes and objects,
- choose MySQL data types for a column, and
- use primary keys and foreign keys to identify rows and link tables.
Why a database?
You could save data in a text file, but that gets hard quickly. How do two users edit it at the same time? How do you find one student among 20,000 without reading the whole file? What stops someone from typing "abc" as a grade?
A database is an organized collection of data. A database management system (DBMS) is the software that stores it and answers requests for it. The DBMS takes care of:
- storing data permanently on disk, even after the program closes,
- finding data fast, even in very large tables,
- letting many users work at once without overwriting each other,
- enforcing rules, such as "every student has an ID" or "a grade is a number", and
- security and backups: who may read or change what.
MySQL is a popular free DBMS, and it's what this course uses. It's a relational DBMS: data is kept in tables that relate to each other. You talk to it in SQL (Structured Query Language), which you'll learn in the next lesson.
Tables, rows, and columns
A relational database holds tables. A table looks like a spreadsheet:
| student_id | first_name | last_name | course | year_level |
|---|---|---|---|---|
| 2024-0001 | Ana | Reyes | BSCS | 1 |
| 2024-0002 | Ben | Cruz | BSIT | 2 |
| 2024-0003 | Cara | Lim | BSCS | 1 |
- A column (or field) is one piece of information, with a name and a data type:
first_name,year_level. - A row (or record) is one item: one student.
- The table is the collection of all rows of one kind:
students.
This should look familiar from OOP. A table is close to a class, its columns are like the fields, and each row is like one object:
| OOP (Java) | Database |
|---|---|
class Student | table students |
field firstName | column first_name |
one Student object | one row |
an ArrayList<Student> in memory | all the rows, saved on disk |
When you connect Java to MySQL later, you'll read each row into an object and write objects back as rows.
Quick check
MySQL data types
Every column has a data type, and MySQL refuses values that don't fit. Choosing the right type keeps data clean. These are the ones you'll use most:
| Type | Holds | Example use |
|---|---|---|
INT | whole numbers | year_level, units, quantities |
DECIMAL(p, s) | exact decimals: p digits in all, s after the point | money: DECIMAL(10,2) holds up to 99,999,999.99 |
DOUBLE | approximate decimals | measurements; not money |
VARCHAR(n) | text up to n characters | names, emails, codes |
TEXT | long text | descriptions, remarks |
CHAR(n) | text of exactly n characters | fixed codes like 'M'/'F' |
DATE | a date, 'YYYY-MM-DD' | birth_date |
DATETIME | a date and time | created_at |
BOOLEAN | true/false (stored as 0 or 1) | is_active |
How the types match Java's:
| MySQL | Java |
|---|---|
INT | int |
DECIMAL | java.math.BigDecimal (or double for simple programs) |
DOUBLE | double |
VARCHAR, CHAR, TEXT | String |
DATE | java.time.LocalDate |
BOOLEAN | boolean |
A few rules of thumb:
- An ID like
2024-0001or a phone number like09171234567is text (VARCHAR), not a number. You never do math with it, and a leading zero must not disappear. - Use
DECIMALfor money.DOUBLEcan't store 0.1 exactly, just like Java'sdouble. - Pick a
VARCHARlength that fits real data with room to spare:VARCHAR(50)for a name,VARCHAR(100)for an email.
Quick check
Primary keys
Two students can have the same name, so how does the database tell rows apart? Every table should have a primary key: a column (or set of columns) whose value is unique for every row and never empty.
Try it · SQL
Press Run. Notice:
AUTO_INCREMENTmakes MySQL number the rows itself: 1, 2, 3. You don't insertidat all.- There are two "Ana Reyes", but their
ids differ, so each row can still be found exactly. NOT NULLmeans the column must have a value.UNIQUEmeans no two rows may share it, sostudent_nocan't repeat either.
A primary key can be a natural key that already exists in the real world (a student number), or a surrogate key made up just for the database (an auto-numbered id). Many developers prefer a surrogate id, because natural keys sometimes change, and keep the natural key UNIQUE as well, as above.
Foreign keys
Tables become useful when they're linked. Say students enroll in subjects. Instead of copying a student's name into every enrollment, the enrollments table stores the student's id. A column that points to the primary key of another table is a foreign key:
Try it · SQL
Ana (id 1) has two enrollments and Ben (id 2) has one. Each student's name is stored once, so if it's misspelled you fix it in one place.
The foreign key also protects the data. The database refuses an enrollment for a student who doesn't exist:
Try it · SQL
Run it and you'll get a foreign key error: there's no student with id 99. This rule is called referential integrity: every reference must point to a real row. It's also why you can't delete a student who still has enrollments, unless you delete the enrollments first.
The link is one-to-many: one student has many enrollments, and each enrollment belongs to one student. The foreign key always goes on the "many" side.
Quick check
Try it: create a table
Exercise · SQL
Create the subjects table
Write a CREATE TABLE subjects statement with three columns: code (text up to 10 characters, the primary key), title (text up to 100 characters, required), and units (a whole number). The INSERT and SELECT below it are already written.
Hint
Each column is a name and a type, separated by commas: code VARCHAR(10) PRIMARY KEY, then title VARCHAR(100) NOT NULL, then units INT. Wrap them in parentheses and end with a semicolon.
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
CREATE TABLE subjects (
code VARCHAR(10) PRIMARY KEY,
title VARCHAR(100) NOT NULL,
units INT
);
INSERT INTO subjects (code, title, units) VALUES
('CS 122', 'Object-Oriented Programming', 3),
('GE 5', 'Purposive Communication', 3),
('PE 2', 'Rhythmic Activities', 2);
SELECT * FROM subjects;
The examples on this page run in your browser on SQLite, a small database that understands nearly the same SQL. MySQL-only lines like CREATE DATABASE and USE are skipped here, and AUTO_INCREMENT is translated for you. In lab, run the same SQL in MySQL.
Setting up MySQL and MySQL Workbench
In lab you'll use the real MySQL server with MySQL Workbench, MySQL's free graphical tool.
- Install MySQL. Download MySQL Installer (Windows) from dev.mysql.com, choose MySQL Server and MySQL Workbench, and set a root password when asked. Write it down. (If your lab uses XAMPP instead, start MySQL from the XAMPP Control Panel; its server is MariaDB, which accepts the same SQL in this course.)
- Connect. Open Workbench and click the Local instance connection (host
localhost, port3306, userroot). Enter the password. - Run SQL. Type statements in the query tab and press the lightning-bolt button (or Ctrl+Shift+Enter) to run them. Results appear in the grid below.
- Look around. The Schemas panel on the left lists databases and their tables. Right-click a table and choose Select Rows to see its data, or Table Inspector to see its columns and keys.
Workbench can also draw your tables as an ER diagram (Database → Reverse Engineer), with lines for the foreign keys. That's a quick way to check that your tables are linked the way you meant.
Common mistakes
- Storing IDs and phone numbers as
INT. They lose leading zeros and can overflow. UseVARCHAR. - Using
DOUBLEfor money. UseDECIMAL(10,2). - A table without a primary key. You then can't update or delete exactly one row.
- Copying the same data into many tables (a student's name in every enrollment) instead of storing an ID and linking with a foreign key.
- Putting the foreign key on the wrong side. It goes in the table on the "many" side.
Summary
- A database stores data permanently and safely; a DBMS such as MySQL manages it, and you talk to it in SQL.
- A table has columns (fields with types) and rows (records), much like a class and its objects.
- Choose types that fit:
INT,DECIMALfor money,VARCHAR(n)for text and IDs,DATEfor dates. - A primary key uniquely identifies each row;
AUTO_INCREMENTnumbers rows automatically. - A foreign key points to another table's primary key and stops references to rows that don't exist.
Next lesson: essential SQL: creating, reading, updating, and deleting data.