Web Programming Step by Step, 2nd Edition
Lecture Extra: Database Definition and Data Manipulation
Reading: 13.2; Appendix B
Except where otherwise noted, the contents of this document are
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst.
All rights reserved.
Any redistribution, reproduction, transmission, or storage of part
or all of the contents in any form is prohibited without the author's
expressed written permission.
CRUD applications
Most web sites do four general tasks ("CRUD") with data in a database:
- Create new rows
- Read existing data (
SELECT
)
- Update / modify values in existing rows
- Delete rows
In lecture we explored only the "R", but now let's examine the others...
Connecting to a server in a terminal
-
You can talk to a database directly using a secure shell (SSH) terminal program such as .
-
Open your SSH program and connect to
webster.cs.washington.edu
.
-
in a Mac/Linux Terminal window, type:
ssh yourUWnetID@webster.cs.washington.edu
-
Log in with your normal UW NetID and password.
The MySQL console
- connect to Webster in an SSH program like , then type:
[stepp@webster ~]$ mysql -u myusername -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
mysql> use imdb_small;
Database changed
mysql> select * from actors where first_name like '%mick%';
+--------+------------+-----------+--------+
| id | first_name | last_name | gender |
+--------+------------+-----------+--------+
| 71699 | Mickey | Cantwell | M |
| 115652 | Mickey | Dee | M |
| 470693 | Mick | Theo | M |
| 716748 | Mickie | McGowan | F |
+--------+------------+-----------+--------+
4 rows in set (0.01 sec)
Learning about databases and tables
SHOW DATABASES;
USE database;
SHOW TABLES;
DESCRIBE table;
mysql> USE simpsons;
mysql> SHOW TABLES;
+-----------+
| students |
| courses |
| grades |
| teachers |
+-----------+
4 rows in set
The SQL statement
INSERT INTO table
VALUES (value, value, ..., value);
INSERT INTO students
VALUES (789, "Nelson", "muntz@fox.com", "haha!");
- adds a new row to the given table
- columns' values should be listed in the same order as in the table
- How would we record that Nelson took CSE 190M and got a D+ in it?
More about INSERT
INSERT INTO table (columnName, columnName, ..., columnName)
VALUES (value, value, ..., value);
INSERT INTO students (name, email)
VALUES ("Lewis", "lewis@fox.com");
- some columns have default or auto-assigned values (such as IDs)
- omitting them from the INSERT statement uses the defaults
The SQL statement
REPLACE INTO table (columnName, columnName, ..., columnName)
VALUES (value, value, ..., value);
REPLACE INTO students
VALUES (789, "Martin", "prince@fox.com");
- just like INSERT, but if an existing row exists for that key (ID), it will be replaced
- can pass optional list of column names, like with INSERT
The SQL statement
UPDATE table
SET column = value,
...,
column = value
WHERE column = value;
UPDATE students
SET email = "lisasimpson@gmail.com"
WHERE id = 888;
- modifies an existing row(s) in a table
- BE CAREFUL! If you omit the WHERE, it modifies ALL rows
The SQL statement
DELETE FROM table
WHERE condition;
DELETE FROM students
WHERE id = 888;
- removes existing row(s) in a table
- can be used with other syntax like LIMIT, LIKE, ORDER BY, etc.
- BE CAREFUL! If you omit the WHERE, it deletes ALL rows
and
an entire database
CREATE DATABASE name;
DROP DATABASE name;
CREATE DATABASE warcraft;
- adds/deletes an entire database from the server
Creating and deleting a table
CREATE TABLE name (
columnName type constraints,
...
columnName type constraints
);
DROP TABLE name;
CREATE TABLE students (
id INTEGER,
name VARCHAR(20),
email VARCHAR(32),
password VARCHAR(16)
);
- adds/deletes a table from this database
- all columns' names and types must be listed (see next slide)
SQL
BOOLEAN | either TRUE or FALSE |
INTEGER | 32-bit integer |
DOUBLE | real number |
VARCHAR(length) | a string, up to the given length |
ENUM(value, ..., value) | a fixed set of values |
DATE , TIME , DATETIME | timestamps (common value: NOW() ) |
BLOB | binary data |
Column constraints
CREATE TABLE students (
id INTEGER UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
email VARCHAR(32),
password VARCHAR(16) NOT NULL DEFAULT "12345"
);
NOT NULL
: not allowed to insert a null/empty value in any row for that column
PRIMARY KEY
/ UNIQUE
: no two rows can have the same value
DEFAULT value
: if no value is provided, use the given default
AUTO_INCREMENT
: default value is the last row's value plus 1 (useful for IDs)
UNSIGNED
: don't allow negative numbers (INTEGER
only)
Rename a table
ALTER TABLE name RENAME TO newName;
ALTER TABLE students RENAME TO children;
- changes the name of an existing table
Add/remove/modify a column in a table
ALTER TABLE name
ADD COLUMN columnName type constraints;
ALTER TABLE name DROP COLUMN columnName;
ALTER TABLE name
CHANGE COLUMN oldColumnName newColumnName type constraints;
- adds/deletes/respecifies a column in an existing table
- if a column is added, all existing rows are given a default value for that column
Granting permission to a user
GRANT permission
ON database.table
TO 'username'@'server';
GRANT SELECT ON simpsons.grades TO 'homer'@'localhost';
GRANT * ON simpsons.* TO 'daisy'@'localhost';
- necessary to give a user permissions (once) before they can use your database
Database Design
-
13.1: Database Basics
-
13.2: SQL
-
13.3: Multi-table Queries
-
13.4: Databases and PHP
-
Appendix B
Database design principles
- database design : the act of deciding the schema for a database
- database schema: a description of what tables a database should have, what columns each table should contain, which columns' values must be unique, etc.
- some database design principles:
- keep it simple, stupid (KISS)
- provide an identifier by which any row can be uniquely fetched
- eliminate redundancy, especially of lengthy data (strings)
- integers are smaller than strings and better to repeat
- favor integer data for comparisons and repeated values
- integers are smaller than strings and better to repeat
- integers can be compared/searched more quickly than strings, real numbers
First database design
student_grades
name | email | course | teacher | grade |
Bart | bart@fox.com | Computer Science 142 | Krabappel | B- |
Bart | bart@fox.com | Computer Science 143 | Hoover | C |
Milhouse | milhouse@fox.com | Computer Science 142 | Krabappel | B+ |
Lisa | lisa@fox.com | Computer Science 143 | Hoover | A+ |
Lisa | lisa@fox.com | Computer Science 190M | Stepp | A+ |
Ralph | ralph@fox.com | Informatics 100 | Krabappel | D+ |
- what's good and bad about this design?
- good: simple (one table), can see all data in one place
- bad: redundancy (name, email, course repeated frequently)
- bad: most searches (e.g. find a student's courses) will have to rely on string comparisons
- bad: there is no single column whose value will be unique in each row
Improved database design
students
id | name | email |
123 | Bart | bart@fox.com |
456 | Milhouse | milhouse@fox.com |
888 | Lisa | lisa@fox.com |
404 | Ralph | ralph@fox.com |
|
courses
id | name | teacher_id |
10001 | Computer Science 142 | 1234 |
10002 | Computer Science 143 | 5678 |
10003 | Computer Science 190M | 9012 |
10004 | Informatics 100 | 1234 |
|
grades
student_id | course_id | grade |
123 | 10001 | B- |
123 | 10002 | C |
456 | 10001 | B+ |
888 | 10002 | A+ |
888 | 10003 | A+ |
404 | 10004 | D+ |
|
teachers
id | name |
1234 | Krabappel |
5678 | Hoover |
9012 | Stepp |
|
- normalizing: splitting tables to improve structure / redundancy (linked by unique IDs)
- primary key: a column guaranteed to be unique for each record (e.g. Lisa Simpson's ID 888)
- foreign key: a column in table A storing a primary key value from table B
- (e.g. records in
grades
with student_id
of 888 are Lisa's grades)
Database design exercise
Suppose we want to write a web store like Amazon.com.
The store sells products that can be purchased by customers online.
The customer can add items to their shopping cart and then order them.
The customer can also check the order's status, whether it has shipped, etc.
- What are some database tables and columns we could use?
- Is your design normalized? Does it have any redundancy?