34
Brief Introduction to DBMS 1 Brief Introduction to DATABASE 1. What is a Database System? Some Reasons for Using a DBMS (Database Management System) Persistence of data Sharing of data between programs Handle concurrent requests for data access Transactions that can be committed or rolled back Report generation Sometimes database means a program for managing data Example: Oracle Corporation is a database company. MySQL is a database. Sometimes database means a collection of data Example: I keep a database of my CD collection on 3 by 5 cards Sometimes database means a set of tables, indexes, and views Example: My program needs to connect to the Airline Reservation database, which uses MySQL 2. Types of Databases Relational: Data is stored in tables Database Management System database Application Programs Application Users Database Management System

Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Embed Size (px)

Citation preview

Page 1: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

1

Brief Introduction to DATABASE

1. What is a Database System?

Some Reasons for Using a DBMS (Database Management System)

Persistence of data

Sharing of data between programs

Handle concurrent requests for data access

Transactions that can be committed or rolled back

Report generation

Sometimes database means a program for managing data

Example:

Oracle Corporation is a database company.

MySQL is a database.

Sometimes database means a collection of data

Example:

I keep a database of my CD collection on 3 by 5 cards

Sometimes database means a set of tables, indexes, and views

Example:

My program needs to connect to the Airline Reservation database, which uses MySQL

2. Types of Databases

Relational: Data is stored in tables

Database Management System

… database

Application Programs

Application Users

Database Management System

Page 2: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

2

Object-Oriented: Tables can be classed and/or sub-classed, and Programmer can define

methods on tables

Object: Objects are stored in the database

3. Relational, Object-Relational, O-O Databases and SQL

Database consists of a number of tables. Table is a collection of records. Each column of

data has a type

Firstname Lastname Phone Code

Bill Clinton 234-6677 2000

George Bush 235-7721 3000

John Kelly 222-7756 5000

Use SQL (Structured Query Language) to access data in the database

Some Available DBMS systems

Oracle, MySQL, DB2, SQL Server, Access, Sybase, etc.

Some Open Source DBMS Systems

Postgres, MySQL community server (??)

4. Rational Database and Relational Data Model

Most of today’s database systems are relational database systems, based on the relational

data model. A relational data model has three key components: structure, integrity and

languages.

Structure defines the representation of the data.

Integrity imposes constraints on the data.

Language provides the means for accessing and manipulating data.

Relational Structure

A relational database consists of a set of relations. A relation has two things in one: a

schema and an instance of the schema. The schema defines the relation and an instance is

the content of the relation at a given time. An instance of a relation is nothing more than a

table with rows and named columns. For convenience with no confusion, we refer

instances of relations as just relations or tables.

Page 3: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

3

Course Table

Student Table

Course Table courseId subjectId courseNumber title numOfCredits

11111 CSCI 1301 Introduction to Java I 4

11112 CSCI 1302 Introduction to Java II 3

11113 CSCI 3720 Database Systems 3

11114 CSCI 4750 Rapid Java Application 3

11115 MATH 2750 Calculus I 5

11116 MATH 3750 Calculus II 5

11117 EDUC 1111 Reading 3 11118 ITEC 1344 Database Administration 3

Columns/Attributes

Tuples/

Rows

Relation/Table Name

Student Table

ssn firstName mi lastName phone birthDate street zipCode deptID

444111110 Jacob R Smith 9129219434 1985-04-09 99 Kingston Street 31435 BIOL

444111111 John K Stevenson 9129219434 null 100 Main Street 31411 BIOL

444111112 George K Smith 9129213454 1974-10-10 1200 Abercorn St. 31419 CS

444111113 Frank E Jones 9125919434 1970-09-09 100 Main Street 31411 BIOL

444111114 Jean K Smith 9129219434 1970-02-09 100 Main Street 31411 CHEM

444111115 Josh R Woo 7075989434 1970-02-09 555 Franklin St. 31411 CHEM

444111116 Josh R Smith 9129219434 1973-02-09 100 Main Street 31411 BIOL

444111117 Joy P Kennedy 9129229434 1974-03-19 103 Bay Street 31412 CS

444111118 Toni R Peterson 9129229434 1964-04-29 103 Bay Street 31412 MATH

444111119 Patrick R Stoneman 9129229434 1969-04-29 101 Washington St. 31435 MATH

444111120 Rick R Carter 9125919434 1986-04-09 19 West Ford St. 31411 BIOL

Page 4: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

4

Enrollment Table

Table vs. File

NOTE:

A table or a relation is not same as a file. Most of the relational database systems store

multiple tables in a file.

Integrity Constraints

An integrity constraint imposes a condition that all legal instances of the relations must

satisfy. In general, there are three types of constraints: domain constraint, primary key

constraint, and foreign key constraint. Domain constraints and primary key constraints

are known as intra-relational constraints, meaning that a constraint involves only one

relation. The foreign key constraint is known as inter-relational, meaning that a

constraint involves more than one relation.

Enrollment Table

ssn courseId dateRegistered grade

444111110 11111 2004-03-19 A

444111110 11112 2004-03-19 B

444111110 11113 2004-03-19 C

444111111 11111 2004-03-19 D

444111111 11112 2004-03-19 F

444111111 11113 2004-03-19 A

444111112 11114 2004-03-19 B

444111112 11115 2004-03-19 C

444111112 11116 2004-03-19 D

444111113 11111 2004-03-19 A

444111113 11113 2004-03-19 A

444111114 11115 2004-03-19 B

444111115 11115 2004-03-19 F

444111115 11116 2004-03-19 F

444111116 11111 2004-03-19 D

444111117 11111 2004-03-19 D

444111118 11111 2004-03-19 A

444111118 11112 2004-03-19 D

444111118 11113 2004-03-19 B

Page 5: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

5

Domain Constraints, Primary Key Constraints, Foreign Key Constraints

Domain Constraints

Domain constraints specify the permissible values for an attribute. Domains can be

specified using standard data types such as integers, floating-point numbers, fixed-length

strings, and variant-length strings. The standard data type specifies a broad range of

values. Additional constraints can be specified to narrow the ranges. You can also specify

whether an attribute can be null.

Example

create table Course(

subjectCode char(4) not null,

courseNumber int not null,

title varchar(50) not null,

numOfCredits int not null

constraint greaterThanOne check (numOfCredits >= 1));

Superkey

A superkey is an attribute or a set of attributes that uniquely identify the relation. That is,

no two tuples have the same values on the superkey. By definition, a relation consists of a

set of distinct tuples. The set of all attributes in the relation forms a superkey.

Key and Candidate Key

courseId subjectId courseNumber title numOfCredits

11111 CSCI 1301 Introduction to Java I 4

11112 CSCI 1302 Introduction to Java II 3

11113 CSCI 3720 Database Systems 3

...

ssn courseId dateRegistered grade

444111110 11111 2004-03-19 A

444111110 11112 2004-03-19 B

444111110 11113 2004-03-19 C

...

Course Table

Each value in the

numOfCredits column must be

greater than 0 and less than 5

Each value in courseId in the

Enrollment table must match a value

in courseId in the Course table

Each row must have a

value for couserId, and

the value must be unique

Enrollment Table

Page 6: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

6

A key K is a minimal superkey, meaning that any proper subset of K is not a superkey. It

is possible that a relation has several keys. In this case, each of the keys is called a

candidate key.

Primary Key

The primary key is one of the candidate keys designated by the database designer. The

primary key is often used to identify tuples in a relation.

create table Course(

subjectCode char(4),

courseNumber int,

title varchar(50), numOfCredits int

constraint greaterThanOne check (numOfCredits >= 1),

primary key (subjectCode, courseNumber));

Primary Key Constraints

The primary key constraint specifies that the primary key value of a tuple cannot be null

and no two tuples in the relation can have the same value on the primary key. The DBMS

enforces the primary key constraint. For example, if you attempt to insert a record with

the same primary key as an existing record in the table, the DBMS would report an error

and reject the operation.

Foreign Key Constraints

In a relational database, data are related. Tuples in a relation are related and tuples in

different relations are related through their common attributes. Informally speaking, the

common attributes are foreign keys. The foreign key constraints define the relationships

among relations.

Formally, a set of attributes FK is a foreign key in a relation R that references relation T if

it satisfies the following two rules:

1. The attributes in FK have the same domain as the primary key in T.

2. A non-null value on FK in R must match a primary key value in T.

create table Enrollment (

ssn char(9),

courseId char(5),

dateRegistered date,

R T

FK

Page 7: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

7

grade char(1),

primary key (ssn, courseId),

foreign key (ssn) references Student,

foreign key (courseId) references Course

);

A foreign key is not necessarily the primary key or part of the primary in the relation. For

example, subjectCode is a foreign key in the Course table that references the Subject

table, but it is not the primary key in Course. departmentCode is a foreign key in the

Subject table that references Department, but it is not the primary key in Subject.

The referencing relation and the referenced relation may be the same table. For example,

supervisorId is a foreign key in Faculty that references facultyId in Faculty.

The foreign key is not necessary to have the same name as its referenced primary key as

long as they have the same domain. For example, headId is a foreign key in Department

that references facultyId in Faculty.

A relation may have more than one foreign key. For example, headId and collegeCode

are both foreign keys in Department.

5. SQL History

Evolution of the SQL Standard

o First standard approved in 1989 (called SQL-89 or SQL1)

o Comprehensive revision in 1992 (SQL-92 or SQL2)

o Third big revision in 1999 (SQL-99 known as SQL3)

o Other revisions known as SQL:2003, SQL:2006 (XML features), SQL:2008

(more object DB features)

Origins of SQL

o Originally called SEQUEL (Structured English Query Language), then SQL

(Structured Query Language)

o Developed at IBM Research for experimental relational DBMS called System-R

in the 1970s

6. SQL Data Definition and Data Types

CREATE statement can be used to:

o Create a named database schema

o Create individual database tables and specify data types for the table attributes, as

well as key, referential integrity, and NOT NULL constraints

o Create named constraints

Other commands can modify the tables and constraints

o DROP and ALTER statements

• (e.g., Example:

ALTER TABLE EMPLOYEE ADD COLUMN JOB VARCHAR(12); The database

users must enter values for the new attribute JOB for each EMPLOYEE tuple.

Page 8: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

8

7. Schema and Catalog Concepts in SQL

An SQL schema is identified by a schema name, and includes an authorization identifier

to indicate the user or account who owns the schema, as well as descriptors for each

element in the schema.

Schema elements include tables, constraints, views, domains, and other constructs (such

as authorization grants) that describe the schema.

Example:

CREATE SCHEMA COMPANY AUTHORIZATION ‘JSmith’;

Catalog – a named collection of schemas in an SQL environment.

SQL environment is an installation of an SQL-compliant RDBMS in a computer system.

A catalog always contains a special schema called INFORMATION-SCHEMA

The CREATE SCHEMA Statement

A DBMS can manage multiple databases

DBA (or authorized users) can use CREATE SCHEMA to have distinct databases; for

example:

CREATE SCHEMA COMPANY AUTHORIZATION 'JSmith'; Each database has a schema name (e.g. COMPANY)

User 'Smith' will be “owner” of schema, can create tables, other constructs in that schema

Table names can be prefixed by schema name if multiple schemas exist (e.g.

COMPANY.EMPLOYEE)

Prefix not needed if there is a “default schema” for the user

The CREATE TABLE Command in SQL

In its simplest form, specifies a new base relation by giving it a name, and specifying each

of its attributes and their data types (INTEGER, FLOAT, DECIMAL(i,j), CHAR(n),

VARCHAR(n), DATE, and other data types)

A constraint NOT NULL may be specified on an attribute

CREATE TABLE DEPARTMENT (

DNAME VARCHAR(15) NOT NULL,

DNUMBER INT NOT NULL,

MGRSSN CHAR(9) NOT NULL,

MGRSTARTDATE DATE );

CREATE TABLE can also specify the primary key, UNIQUE keys, and referential

integrity constraints (foreign keys)

Via the PRIMARY KEY, UNIQUE, and FOREIGN KEY phrases

CREATE TABLE DEPARTMENT (

DNAME VARCHAR(15) NOT NULL,

DNUMBER INT NOT NULL,

MGRSSN CHAR(9) NOT NULL,

MGRSTARTDATE DATE,

PRIMARY KEY (DNUMBER),

UNIQUE (DNAME),

FOREIGN KEY(MGRSSN) REFERENCES EMPLOYEE (SSN));

Page 9: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

9

Indices

Indices make accessing faster

Primary keys automatically have an index

The CREATE INDEX command creates indices

CREATE INDEX dname_index on DEPARTMENT (DNAME);

8.Understanding Database based on MySQL

Connecting to the Database

Can be done with:

Mysql command line tool - mysql

GUI clients

Program

Examples (by MySQL command line tool)

You can choose mysqld as a service, or mysqld as a standalone daemon.

mysqld --standalone

C:\mysql\bin\mysqld --standalone –debug

mysqladmin" –p -u root shutdown

$mysql –h localhost –u user –p

GUI Clients

MySQL Workbench

SQL Syntax

Names

Databases, table columns & indexes have names

Legal Characters

Alphanumeric characters, '_', '$'

Names can start with:

Letter

Underscore

Letter with diacritical marks and some non-latin letters

Name length

64 characters - MySQL

Names are not case sensitive

Page 10: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

10

Data Types

Numeric Values

Integer: decimal or hexadecimal

Floating-point: scientific, real number (e.g., 12.1234)

String Values

MySQL example: ‘this is a string’ or “this is a string”

Escape Sequence

\' Single quote

\b Backspace

\n Newline

\r Tab

\\ Backslash

Comments (MySQL example)

-- this is a comment

/* this is a comment */

#this is a comment

Numeric Data

Types

Numeric(10, 2) defines a number with maximum of 10 digits with 2 of the 10 to the right

of the decimal point (e.g., 12345678.91)

Decimal and numeric are different names for the same type.

Page 11: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

11

String Types

Type Description

char(n) Fixed-length blank padded

varchar(n) Variable-length with limit

text Variable unlimited length

Blob (MySQL) Variable (not specifically limited) length binary string

char & varchar are the most common string types

char is fixed-width: shorter strings are padded (with blanks)

text can be of any size

MySQL limits char and varchar to 255 characters

Dates

DATETIME – ‘YYYY-MM-DD HH:MM

DATE – ‘YYYY-MM-DD’ format

TIMESTAMP

Basically now is same as DATETIME

Common SQL Statements

SELECT Retrieves data from table(s)

INSERT Adds row(s) to a table

UPDATE Change field(s) in record(s)

DELETE Removes row(s) from a table Data Definition

CREATE

TABLE

Define a table and its columns (fields)

DROP TABLE Deletes a table

ALTER TABLE Adds a new column, add/drop primary key

CREATE

INDEX

Create an index

DROP INDEX Delete an index

CREATE VIEW Define a logical table from other table(s) view(s)

DROP VIEW Deletes a view

CREATE DATABASE

General Form

CREATE DATABASE [IF NOT EXISTS] db_name

[create_specification [, create_specification] ...]

create_specification:

[DEFAULT] CHARACTER SET charset_name

| [DEFAULT] COLLATE collation_name

(Example)

mysql> create database DBMSExamples;

Query OK, 1 row affected (0.00 sec)

Page 12: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

12

USE

Sets a default database for subsequent queries

General Form

USE db_name

(Example)

mysql> use DBMSExamples;

Database changed

CREATE TABLE

General Form

CREATE TABLE table_name (

col_name col_type [ NOT NULL | PRIMARY KEY]

[, col_name col_type [ NOT NULL | PRIMARY KEY]]*

)

mysql> use DBMSExamples;

Database changed

(Example)

Mysql> CREATE TABLE students

-> (

-> firstname CHAR(20) NOT NULL,

-> lastname CHAR(20),

-> phone CHAR(10),

-> code INTEGER

-> );

Query OK, 0 rows affected (0.61 sec)

mysql> CREATE TABLE codes

-> (

-> code INTEGER,

-> name CHAR(20)

-> );

Query OK, 0 rows affected (0.63 sec)

mysql> DESCRIBE students

-> ;

+-----------+----------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-----------+----------+------+-----+---------+-------+

| firstname | char(20) | NO | | | |

| lastname | char(20) | YES | | NULL | |

| phone | char(10) | YES | | NULL | |

| code | int(11) | YES | | NULL | |

+-----------+----------+------+-----+---------+-------+

Page 13: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

13

4 rows in set (0.11 sec)

mysql> desc students;

+-----------+----------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-----------+----------+------+-----+---------+-------+

| firstname | char(20) | NO | | | |

| lastname | char(20) | YES | | NULL | |

| phone | char(10) | YES | | NULL | |

| code | int(11) | YES | | NULL | |

+-----------+----------+------+-----+---------+-------+

4 rows in set (0.00 sec)

mysql> explain students

-> \g

+-----------+----------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-----------+----------+------+-----+---------+-------+

| firstname | char(20) | NO | | | |

| lastname | char(20) | YES | | NULL | |

| phone | char(10) | YES | | NULL | |

| code | int(11) | YES | | NULL | |

+-----------+----------+------+-----+---------+-------+

4 rows in set (0.00 sec)

mysql> show columns from students

-> ;

+-----------+----------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-----------+----------+------+-----+---------+-------+

| firstname | char(20) | NO | | | |

| lastname | char(20) | YES | | NULL | |

| phone | char(10) | YES | | NULL | |

| code | int(11) | YES | | NULL | |

+-----------+----------+------+-----+---------+-------+

4 rows in set (0.02 sec)

mysql> show fields from students \g

+-----------+----------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-----------+----------+------+-----+---------+-------+

| firstname | char(20) | NO | | | |

| lastname | char(20) | YES | | NULL | |

| phone | char(10) | YES | | NULL | |

| code | int(11) | YES | | NULL | |

+-----------+----------+------+-----+---------+-------+

4 rows in set (0.00 sec)

SELECT

Gets the data from one or more tables

Page 14: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

14

General Form

SELECT [STRAIGHT_JOIN]

[SQL_SMALL_RESULT] [SQL_BIG_RESULT]

[SQL_BUFFER_RESULT] [SQL_CACHE | SQL_NO_CACHE]

[SQL_CALC_FOUND_ROWS] [HIGH_PRIORITY]

[DISTINCT | DISTINCTROW | ALL]

select_expression,...

[INTO {OUTFILE | DUMPFILE} 'file_name' export_options]

[FROM table_references

[WHERE where_definition]

[GROUP BY {unsigned_integer | col_name | formula} [ASC | DESC], ...

[WITH ROLLUP]]

[HAVING where_definition]

[ORDER BY {unsigned_integer | col_name | formula} [ASC | DESC] ,...]

[LIMIT [offset,] row_count | row_count OFFSET offset]

[PROCEDURE procedure_name(argument_list)]

[FOR UPDATE | LOCK IN SHARE MODE]]

mysql> SELECT * FROM students;

Empty set (0.00 sec)

INSERT

Add data to a table

General Form

INSERT [LOW_PRIORITY | DELAYED] [IGNORE]

[INTO] tbl_name [(col_name,...)]

VALUES ((expression | DEFAULT),...),(...),...

[ ON DUPLICATE KEY UPDATE col_name=expression, ... ]

(Example)

mysql> INSERT

-> INTO students (firstname, lastname, phone. Code)

-> VALUES ('bill', 'clinton', '123-4567’,2000);

Query OK, 1 row affected (0.50 sec)

mysql> INSERT

-> INTO codes (code, name)

-> VALUES (2000, 'marginal' );

Query OK, 1 row affected (0.48 sec)

mysql> SELECT firstname , phone FROM students;

+-----------+----------+

| firstname | phone |

+-----------+----------+

| bill | 123-4567 |

+-----------+----------+

1 row in set (0.00 sec)

Page 15: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

15

mysql> SELECT lastname, name

-> FROM students, codes

-> WHERE students.code = codes.code;

+----------+----------+

| lastname | name |

+----------+----------+

| clinton | marginal |

+----------+----------+

1 row in set (0.01 sec)

mysql> SELECT students.lastname, codes.name

-> FROM students, codes

-> WHERE students.code = codes.code;

+----------+----------+

| lastname | name |

+----------+----------+

| clinton | marginal |

+----------+----------+

1 row in set (0.44 sec)

mysql>

Update

Modify existing data in a database

General Form

UPDATE [LOW_PRIORITY] [IGNORE] tbl_name [, tbl_name ...]

SET col_name1=expr1 [, col_name2=expr2 ...]

[WHERE where_definition]

Example

mysql> update students

-> set firstname='Hilary'

-> where lastname="Clinton";

Query OK, 1 row affected (0.52 sec)

Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from students;

+-----------+----------+----------+------+

| firstname | lastname | phone | code |

+-----------+----------+----------+------+

| Hilary | clinton | 123-4567 | 2000 |

+-----------+----------+----------+------+

1 row in set (0.00 sec)

mysql> ALTER TABLE students ADD column foo CHAR(40);

Query OK, 1 row affected (0.03 sec)

Records: 1 Duplicates: 0 Warnings: 0

mysql> DROP TABLE students;

Page 16: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

16

Query OK, 0 rows affected (0.01 sec)

mysql> DROP DATABASE databaseexamples;

Query OK, 0 rows affected (0.00 sec)

9. JDBC (Java Database Connectivity-- – Connecting to DBMS)

Oracle JDBC Tutorial & Documentation

http://docs.oracle.com/javase/tutorial/jdbc/basics/

Connector-J, MySql JDBC Driver Documentation,

http://dev.mysql.com/usingmysql/java/

JDBC Drivers

Java supports four types of JDBC drivers

JDBC-ODBC bridge plus ODBC driver: Java code access ODBC native binary drivers,

ODBC driver accesses databases, ODBC drivers must be installed on each client

Native-API partly-Java driver: Java code accesses database specific native binary drivers

JDBC-Net pure Java driver: Java code accesses database via DBMS-independent net

protocol

Pure Java driver

In a pure Java-based driver that communicates directly with vendor's database through

socket connection. This is the highest performance driver available for the database and is

usually provided by the vendor itself.

Page 17: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

17

This kind of driver is extremely flexible, you don't need to install special software on the

client or server. Further, these drivers can be downloaded dynamically.

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their

network protocols, database vendors usually supply type 4 drivers.

The JDBC API is comprised of two packages: java.sql

javax.sql

The JDBC Interfaces

Driver

Connection Connection

Statement Statement Statement Statement

ResultSet ResultSet ResultSet ResultSet

Page 18: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

18

Developing JDBC Programs

Statement to load a driver:

Class.forName("JDBCDriverClass");

A driver is a class. For example:

Database Driver Class Source

Access sun.jdbc.odbc.JdbcOdbcDriver Already in JDK

MySQL com.mysql.jdbc.Driver

Oracle oracle.jdbc.driver.OracleDriver

Connection connection = DriverManager.getConnection(databaseURL);

Database URL Pattern

Access jdbc:odbc:dataSource

MySQL jdbc:mysql://hostname/dbname

Oracle jdbc:oracle:thin:@hostname:port#:oracleDBSID

Examples:

For Access:

Connection connection = DriverManager.getConnection

("jdbc:odbc:ExampleMDBDataSource");

For MySQL:

Connection connection = DriverManager.getConnection

("jdbc:mysql://localhost/test");

For Oracle:

Connection connection = DriverManager.getConnection

("jdbc:oracle:thin:@company.com:1521:orcl", "bob", "feiner");

Creating statement:

Statement statement = connection.createStatement();

Executing statement (for update, delete, insert):

statement.executeUpdate

("create table Temp (col1 char(5), col2 char(5))");

Executing statement (for select):

// Select the columns from the Student table

ResultSet resultSet = statement.executeQuery

("select firstName, mi, lastName from Student where lastName "

+ " = 'Smith'");

Executing statement (for select):

// Select the columns from the Student table

ResultSet resultSet = stmt.executeQuery

Page 19: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

19

("select firstName, mi, lastName from Student where lastName "

+ " = 'Smith'");

Processing ResultSet (for select):

// Iterate through the result and print the student names

while (resultSet.next())

System.out.println(resultSet.getString(1) + " " + resultSet.getString(2)

+ ". " + resultSet.getString(3));

Queries

executeUpdate

Use for INSERT, UPDATE, DELETE or SQL that return nothing

executeQuery

Use for SQL (SELECT) that return a result set

execute

Use for SQL that return multiple result sets

Uncommon

ResultSet

ResultSet - Result of a Query

- JDBC returns a ResultSet as a result of a query

- A ResultSet contains all the rows and columns that satisfy the SQL statement

- A cursor is maintained to the current row of the data

Page 20: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

20

- The cursor is valid until the ResultSet object or its Statement object is closed

- next() method advances the cursor to the next row

- You can access columns of the current row by index or name

ResultSet has getXXX methods that:

has either a column name or column index as argument

returns the data in that column converted to type XXX

getObject

- An alternative to the getXXX method

Rather than

ResultSet tableList =

getTables.executeQuery("SELECT * FROM name");

String firstName = tableList.getString( 1);

- Can use

ResultSet tableList =

getTables.executeQuery("SELECT * FROM name");

String firstName = (String) tableList.getObject( 1);

getObject( int k) returns the object in the k’th column of the current row

getObject( String columnName) returns the object in the named column

PreparedStatement

The PreparedStatement interface is designed to execute dynamic SQL statements and

SQL-stored procedures with IN parameters. These SQL statements and stored procedures

are precompiled for efficient use when repeatedly executed.

Statement pstmt = connection.prepareStatement

("insert into Student (firstName, mi, lastName) +

values (?, ?, ?)");

Retrieving Database Metadata

Database metadata is the information that describes database itself. JDBC provides the

DatabaseMetaData interface for obtaining database wide information and the

ResultSetMetaData interface for obtaining the information on the specific ResultSet.

The DatabaseMetaData interface provides more than 100 methods for getting database

metadata concerning the database as a whole. These methods can be divided into three

groups: for retrieving general information, for finding database capabilities, and for

getting object descriptions.

The general information includes the URL, username, product name, product version,

driver name, driver version, available functions, available data types and so on.

Example:

DatabaseMetaData dbMetaData = connection.getMetaData();

Page 21: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

21

System.out.println("database URL: " + dbMetaData.getURL());

System.out.println("database username: " +

dbMetaData.getUserName());

System.out.println("database product name: " +

dbMetaData.getDatabaseProductName());

System.out.println("database product version: " +

dbMetaData.getDatabaseProductVersion());

System.out.println("JDBC driver name: " +

dbMetaData.getDriverName());

System.out.println("JDBC driver version: " +

dbMetaData.getDriverVersion());

System.out.println("JDBC driver major version: " +

new Integer(dbMetaData.getDriverMajorVersion()));

System.out.println("JDBC driver minor version: " +

new Integer(dbMetaData.getDriverMinorVersion()));

System.out.println("Max number of connections: " +

new Integer(dbMetaData.getMaxConnections()));

System.out.println("MaxTableNameLentgh: " +

new Integer(dbMetaData.getMaxTableNameLength()));

System.out.println("MaxColumnsInTable: " +

new Integer(dbMetaData.getMaxColumnsInTable()));

connection.close();

CallableStatement

The CallableStatement interface is used to execute SQL-stored procedure/function.

Example:

drop function if exists studentFound;

delimiter //

create function studentFound(first VARCHAR(20), last VARCHAR(20))

returns int

begin

declare result int;

select count(*) into result

from Student

where Student.firstName = first and

Student.lastName = last;

return result;

end;

//

Page 22: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

22

delimiter ;

mysql> select studentFound('king', 'Smith');

CallableStatement callableStatement = conn.prepareCall(

"{? = call studentFound(?, ?)}");

java.util.Scanner input = new java.util.Scanner(System.in);

String firstName = "Jacob";

String lastName = "Smith";

callableStatement.setString(2, firstName);

callableStatement.setString(3, lastName);

callableStatement.registerOutParameter(1, Types.INTEGER);

callableStatement.execute();

if (callableStatement.getInt(1) >= 1) {

out.println(firstName + " " + lastName

+ " is in the database" + "<br>");

} else {

out.println(firstName + " " + lastName

+ " is not in the database" + "<br>");

Data Conversion

Page 23: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

23

Some Cautions

Mixing ResultSets

Can't have two active result sets on same statement

Connection rugby;

rugby = DriverManager.getConnection( dbUrl, user, password);

Statement getTables = rugby.createStatement();

ResultSet count =

getTables.executeQuery("SELECT COUNT(*) FROM name");

ResultSet tableList =

getTables.executeQuery("SELECT * FROM name");

while (tableList.next() )

System.out.println("Last Name: " + tableList.getObject(1) + '\t' +

"First Name: " + tableList.getObject( "first_name"));

// Raises java.sql.SQLException

count.getObject(1);

rugby.close();

this can happen when two threads have access to the same statement

Two Statements on one Connection work

Connection rugby;

rugby = DriverManager.getConnection( dbUrl, user, password);

Statement getTables = rugby.createStatement();

Statement tableSize = rugby.createStatement();

ResultSet count =

getTables.executeQuery("SELECT COUNT(*) FROM name");

ResultSet tableList =

tableSize.executeQuery("SELECT * FROM name");

while (tableList.next() )

System.out.println("Last Name: " + tableList.getObject(1) + '\t' +

"First Name: " + tableList.getObject( "first_name"));

count.next();

System.out.println("Count: " + count.getObject(1) );

count.close();

tableList.close();

rugby.close();

Threads & Connections

- Some JDBC drivers are not thread safe

- If two threads access the same connection results may get mixed up

MySql driver is thread safe

- When two threads make a request on the same connection

- The second thread blocks until the first thread get it its results

- Can use more than one connection but

- Each connection requires a process on the database

Page 24: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

24

10. Some Data Modeling Terms and JOIN operations

Entity: a distinct class of things about which something is known

Entity Occurrence: particular instance of an entity class. In a database entity occurrences

are records in a table

Attribute: an abstraction belonging to or characteristic of an entity

Primary Key (unique identifier): an attribute (or set of attributes) that uniquely defines an

entity

Relationship: an abstraction belonging to or characteristic of two entities or parts together

Foreign Key: a unique identifier in a record representing another record

Entity Relationship (ER) Diagram

Crow’s Foot ERD

Entity (car) with:

Attributes (Color, make, model, serial number)

Primary key (serial number)

Relationship between Car and Person entities. Car must have one and only one owner.

Person may own zero, one or more cars. Person can own many cars

Page 25: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

25

Page 26: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

26

ER to Relational mapping

ER-to-Relational Mapping Algorithm

COMPANY database example

Assume that the mapping will create tables with simple single-valued attributes

Step 1: Mapping of Regular Entity Types

For each regular entity type, create a relation R that includes all the simple

attributes of E

Called entity relations

• Each tuple represents an entity instance

Step 2: Mapping of Weak Entity Types

For each weak entity type, create a relation R and include all simple attributes of

the entity type as attributes of R

Include primary key attribute of owner as foreign key attributes of R

Step 3: Mapping of Binary 1:1 Relationship Types

For each binary 1:1 relationship type

• Identify relations that correspond to entity types participating in R

Possible approaches:

• Foreign key approach

• Merged relationship approach

• Crossreference or relationship relation approach

Page 27: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

27

Step 4: Mapping of Binary 1:N Relationship Types

For each regular binary 1:N relationship type

• Identify relation that represents participating entity type at N-side of

relationship type

• Include primary key of other entity type as foreign key in S

• Include simple attributes of 1:N relationship type as attributes of S

Alternative approach

• Use the relationship relation (cross-reference) option as in the third

option for binary 1:1 relationships

Step 5: Mapping of Binary M:N Relationship Types

For each binary M:N relationship type

• Create a new relation S

• Include primary key of participating entity types as foreign key attributes

in S

• Include any simple attributes of M:N relationship type

Step 6: Mapping of Multivalued Attributes

For each multivalued attribute

• Create a new relation

• Primary key of R is the combination of A and K

• If the multivalued attribute is composite, include its simple components

Step 7: Mapping of N-ary Relationship Types

For each n-ary relationship type R

• Create a new relation S to represent R

• Include primary keys of participating entity types as foreign keys

• Include any simple attributes as attributes

Page 28: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

28

JOIN Operations

Primary Key

A primary key is one that uniquely identifies a row in a table.

A Simple Faculty Table

name faculty_id

Brown 1

Clinton 2

Bush 3

CREATE TABLE faculty (

name CHAR(20) NOT NULL,

faculty_id INTEGER AUTO_INCREMENT PRIMARY KEY

);

Adding Values

INSERT INTO faculty ( name) VALUES ('White');

INSERT INTO faculty ( name) VALUES ('Beck');

INSERT INTO faculty ( name) VALUES ('Anantha');

INSERT INTO faculty ( name) VALUES ('Vinge');

select * from faculty;

Page 29: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

29

Result

name | faculty_id

----------------------+-------------

White | 1

Beck | 2

Anantha | 3

Vinge | 4

(4 rows)

CREATE TABLE office_hours (

start_time TIME NOT NULL,

end_time TIME NOT NULL,

day CHAR(3) NOT NULL,

faculty_id INTEGER REFERENCES faculty ,

office_hour_id INTEGER AUTO_INCREMENT PRIMARY KEY

);

faculty_id is a foreign key

REFERENCES faculty insures that only valid references are made

start_time end_time day faculty_id office_hour_id

10:00 11:00 Wed 1 1

8:00 12:00 Mon 2 2

17:00 18:30 Tue 1 3

9:00 10:30 Tue 3 4

9:00 10:30 Thu 3 5

15:00 16:00 Fri 1 6

INSERT

INTO office_hours ( start_time, end_time, day, faculty_id )

VALUES ( '10:00:00', '11:00:00' , 'Wed', 1 );

The problem is that we need to know the id for the faculty

Using Select

INSERT INTO

office_hours (start_time, end_time, day, faculty_id )

SELECT

'8:00:00' AS start_time,

'12:00:00' AS end_time,

'Fri' AS day,

faculty_id AS faculty_id

FROM

Page 30: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

30

faculty

WHERE

name = 'Beck';

Getting Office Hours

SELECT

name, start_time, end_time, day

FROM

office_hours, faculty

WHERE

faculty.faculty_id = office_hours.faculty_id;

mysql> SELECT

-> name, start_time, end_time, day

-> FROM

-> office_hours, faculty

-> WHERE

-> faculty.faculty_id = office_hours.faculty_id;

+---------+------------+----------+-----+

| name | start_time | end_time | day |

+---------+------------+----------+-----+

| White | 10:00:00 | 11:00:00 | Wed |

| Beck | 08:00:00 | 12:00:00 | Mon |

| White | 17:00:00 | 12:30:00 | Tue |

| Anantha | 09:00:00 | 10:30:00 | Tue |

| Anantha | 09:00:00 | 10:30:00 | Thu |

| White | 15:00:00 | 16:00:00 | Fri |

+---------+------------+----------+-----+

6 rows in set (0.00 sec)

mysql>

name start_time end_time day

Whitney 10:00:00 11:00:00 Wed

Beck 08:00:00 12:00:00 Mon

Whitney 17:00:00 18:30:00 Tue

Whitney 15:00:00 16:00:00 Fri

Anantha 09:00:00 10:30:00 Tue

Anantha 09:00:00 10:30:00 Thu

Some Selection

SELECT

name, start_time, end_time, day

FROM

office_hours, faculty

WHERE

Page 31: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

31

faculty.faculty_id = office_hours.faculty_id

AND

start_time > '09:00:00'

AND

end_time < '16:30:00'

ORDER BY

Name;

name start_time end_time day

white 10:00:00 11:00:00 Wed

white 15:00:00 16:00:00 Fri

Joins

People

id first_name last_name

1 Roger Whitte

2 Leland Beck

3 Carl Eckberg

Email_Addresses

id user_name host person_id

1 beck cs.lehman.edu 2

2 white cs.lehman.edu 1

3 white cs2.lehman.edu 1

4 foo cs2.lehman.edu

The tables have a column in common as email_addresses.person_id refers to people.id. So we can

create a new table by joining the two tables together on that column

Inner Join (or just Join)

Only uses entries linked in two tables

first_name last_name user_name host

Leland Beck beck cs.sdsu.edu

Roger white white cs.sdsu.edu

Roger White white rohan.sdsu.edu

select

first_name, last_name, user_name, host

from

people, email_address

where

Page 32: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

32

people.id = email_address.person_id;

or equivalently

select

first_name, last_name, user_name, host

from

people inner join email_address

on

(people.id = email_address.person_id);

mysql> select

-> first_name, last_name, user_name, host

-> from

-> people, email_address

-> where

-> people.id = email_address.person_id;

+------------+-----------+-----------+----------------+

| first_name | last_name | user_name | host |

+------------+-----------+-----------+----------------+

| Leland | Beck | beck | cs.lehman.edu |

| Roger | White | white | cs.lehman.edu |

| Roger | White | white | cs2.lehman.edu |

+------------+-----------+-----------+----------------+

3 rows in set (0.00 sec)

mysql> select

-> first_name, last_name, user_name, host

-> from

-> people inner join email_address

-> on

-> (people.id = email_address.person_id);

+------------+-----------+-----------+----------------+

| first_name | last_name | user_name | host |

+------------+-----------+-----------+----------------+

| Leland | Beck | beck | cs.lehman.edu |

| Roger | White | white | cs.lehman.edu |

| Roger | White | white | cs2.lehman.edu |

+------------+-----------+-----------+----------------+

3 rows in set (0.00 sec)

mysql>

Outer Join

Uses all entries from a table

Left Outer Join

Use all entries from the left table

Page 33: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

33

first_name last_name user_name host

Leland Beck beck cs.lehman.edu

Roger White white cs.lehman.edu

Roger White white cs2.lehman.edu

Carl Eckberg

select

first_name, last_name, user_name, host

from

people left outer join email_address

on

(people.id = email_address.person_id);

Right Outer Join

first_name last_name user_name host

Leland Beck beck cs.lehman.edu

Roger white white cs.lehman.edu

Roger Whitney whitney cs2.lehman.edu

foo cs2..lehman.edu

Use all entries from the right table

select

first_name, last_name, user_name, host

from

people right outer join email_address

on

(people.id = email_address.person_id);

A right outer join B & B left outer join A

The following two statements are equivalent

select

first_name, last_name, user_name, host

from

people right outer join email_address

on

(people.id = email_address.person_id);

select

first_name, last_name, user_name, host

Page 34: Brief Introduction to DATABASE 1. What is a Database …comet.lehman.cuny.edu/jung/cmp436774/dbms-intro.pdf · Brief Introduction to DATABASE « 1. What is a Database ... Types of

Brief Introduction to DBMS

34

from

email_address left outer join people

on

(people.id = email_address.person_id);

11. Normalization

The normal forms defined in relational database theory represent guidelines for record design.

The guidelines corresponding to first through fifth normal forms are presented here, in terms that

do not require an understanding of relational theory. The design guidelines are meaningful even if

one is not using a relational database system. We present the guidelines without referring to the

concepts of the relational model in order to emphasize their generality, and also to make them

easier to understand. Our presentation conveys an intuitive sense of the intended constraints on

record design, although in its informality it may be imprecise in some technical details.

The normalization rules are designed to prevent update anomalies and data inconsistencies. With

respect to performance tradeoffs, these guidelines are biased toward the assumption that all non-

key fields will be updated frequently. They tend to penalize retrieval, since data which may have

been retrievable from one record in an un-normalized design may have to be retrieved from

several records in the normalized form. There is no obligation to fully normalize all records when

actual performance requirements are taken into account.

1st, 2

nd, 3

rd, BCNF will be discussed.

12. Object relational Mapping (ORM)

Will be updated

13. Views, Stored Procedures(Functions), Trigger Examples will be added if necessary