comp 321 week 4. overview normalization entity-relationship diagrams sql jdbc/jdbc drivers hsqldb...

32
COMP 321 COMP 321 Week 4 Week 4

Upload: linda-tucker

Post on 17-Jan-2016

233 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

COMP 321COMP 321

Week 4Week 4

Page 2: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

OverviewOverview

NormalizationNormalization

Entity-Relationship DiagramsEntity-Relationship Diagrams

SQLSQL

JDBC/JDBC DriversJDBC/JDBC Drivers

hsqldbhsqldb

Lab 4-1 IntroductionLab 4-1 Introduction

Page 3: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Relational DatabasesRelational Databases

Store data in tables made up of rows and Store data in tables made up of rows and columnscolumns

Columns have data typesColumns have data types

Rows represent entriesRows represent entries

Page 4: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Relational DatabasesRelational Databases

Product_CodeProduct_Code DescriptionDescription PricePrice

116-064116-064 ToasterToaster 24.9524.95

257-535257-535 Hair DryerHair Dryer 29.9529.95

643-119643-119 Car VacuumCar Vacuum 19.9919.99

CREATE TABLE Product( Product_Code CHAR(11), Description CHAR(40), Price DECIMAL(10, 2))

Page 5: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

NormalizationNormalization

What’s wrong with this table definition?What’s wrong with this table definition?

CREATE TABLE Order( Product_Code CHAR(11), Quantity INTEGER, Description CHAR(40), Price DECIMAL(10, 2))

Page 6: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

NormalizationNormalization

What’s wrong with this table definition?What’s wrong with this table definition?

CREATE TABLE Order(Order_Id INTEGER,Product_Code CHAR(11),Quantity INTEGER,Description CHAR(40),Price DECIMAL(10, 2))

Page 7: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Avoid Duplication – Create Two TablesAvoid Duplication – Create Two Tables

CREATE TABLE Order(Order_Id INTEGER PRIMARY KEY,Product_Code CHAR(11),Quantity INTEGER)

CREATE TABLE Product(Product_Code CHAR(11) PRIMARY KEY,Description CHAR(40),Price DECIMAL(10, 2))

Page 8: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Learning Activity 1Learning Activity 1

Problem description:Problem description:– Normalize the following database definition. Normalize the following database definition.

The intention is to represent an order with The intention is to represent an order with information about the customer, the order, information about the customer, the order, and multiple line items.and multiple line items.

Page 9: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Learning Activity 2Learning Activity 2

Problem description:Problem description:– Draw an entity-relationship diagram for the Draw an entity-relationship diagram for the

tables you designed for storing orders.tables you designed for storing orders.

Page 10: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

SQLSQL

Four basic statements:Four basic statements:o SELECT - selects data from tablesSELECT - selects data from tableso INSERT - inserts new data into a tableINSERT - inserts new data into a tableo UPDATE - modifies existing rows in a tableUPDATE - modifies existing rows in a tableo DELETE - removes rows from a tableDELETE - removes rows from a table

Page 11: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

SQL (cont’d)SQL (cont’d)

SELECT * FROM CustomerSELECT * FROM Customer– Selects all columns from Customer tableSelects all columns from Customer table

SELECT City, State FROM CustomerSELECT City, State FROM Customer– Selects only the City and State columnsSelects only the City and State columns

SELECT * FROM Customer WHERE SELECT * FROM Customer WHERE State = ‘CA’State = ‘CA’– Selects all customers who live in CASelects all customers who live in CA

SELECT COUNT(*) FROM Customer SELECT COUNT(*) FROM Customer WHERE State = ‘CA’WHERE State = ‘CA’– Counts number of rows where State is CACounts number of rows where State is CA

Page 12: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

SQL (cont’d)SQL (cont’d)

INSERT INTO Customer VALUES (‘John Doe’, INSERT INTO Customer VALUES (‘John Doe’, ‘Columbus’, ‘OH’)‘Columbus’, ‘OH’)– Inserts a new customer recordInserts a new customer record

UPDATE Customer SET State = ‘OH’ WHERE UPDATE Customer SET State = ‘OH’ WHERE State = ‘CA’State = ‘CA’– Moves all customers who live in CA to OHMoves all customers who live in CA to OH

DELETE FROM CustomerDELETE FROM Customer– Deletes all rows from the Customer tableDeletes all rows from the Customer table

DELETE FROM Customer WHERE State = DELETE FROM Customer WHERE State = ‘CA’‘CA’– Deletes all customers who live in CADeletes all customers who live in CA

Page 13: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

JDBCJDBC

JJava ava DDataataBBase ase CConnectivity - a set of onnectivity - a set of classes and interfaces defined in the classes and interfaces defined in the java.sqljava.sql package package

Allows Java applications to connect to Allows Java applications to connect to databases in a (mostly) database-databases in a (mostly) database-independent wayindependent way

Page 14: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

JDBC (cont’d)JDBC (cont’d)

The classes in The classes in java.sqljava.sql are defined in a are defined in a generic way, so they can be used with generic way, so they can be used with many databasesmany databases

The database-specific code is contained in The database-specific code is contained in a driver, which is usually provided by the a driver, which is usually provided by the database vendordatabase vendor

Drivers are manipulated using the Drivers are manipulated using the DriverManagerDriverManager class from class from java.sqljava.sql

Page 15: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

JDBCJDBC

Page 16: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

JDBC Driver TypesJDBC Driver Types

Type 1: JDBC-ODBC BridgeType 1: JDBC-ODBC Bridge

Type 2: Native API DriverType 2: Native API Driver

Type 3: Network Protocol DriverType 3: Network Protocol Driver

Type 4: Native Protocol DriverType 4: Native Protocol Driver

Page 17: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Type 1 - JDBC - ODBC BridgeType 1 - JDBC - ODBC Bridge

Pros: Database Pros: Database independentindependent

Cons:Cons:– Windows onlyWindows only– PerformancePerformance– ODBC driver must be ODBC driver must be

presentpresent

Page 18: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Type 2 – Native API DriverType 2 – Native API Driver

Pros: better Pros: better performance vs. type 1performance vs. type 1

Cons:Cons:– Client library must be Client library must be

presentpresent– Platform-dependantPlatform-dependant

Page 19: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Type 3 - Network Protocol DriverType 3 - Network Protocol Driver

Pros:Pros:– No database library on No database library on

clientclient– Client is DB-independentClient is DB-independent

Cons:Cons:– Extra layerExtra layer– DB-specific coding DB-specific coding

required in middlewarerequired in middleware

Page 20: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Type 4 – Native Protocol DriverType 4 – Native Protocol Driver

Pros:Pros:– Best performanceBest performance– Pure JavaPure Java

Cons:Cons:– Driver required for Driver required for

each databaseeach database

Page 21: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Using JDBCUsing JDBC

Identify type of driver neededIdentify type of driver needed

Obtain/Install driverObtain/Install driver

Add driver to classpath (In Eclipse, Add driver to classpath (In Eclipse, configure build path)configure build path)

Page 22: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Making a Connection to the DBMaking a Connection to the DB

Manually load the driver classManually load the driver class**::Class.forName("org.hsqldb.jdbcDriver");Class.forName("org.hsqldb.jdbcDriver");

Establish connectionEstablish connectionconn = DriverManager.getConnection(conn = DriverManager.getConnection( "jdbc:hsqldb:hsql://localhost:9001","jdbc:hsqldb:hsql://localhost:9001", "sa", // username"sa", // username ""); // password""); // password

DriverManager takes care of detailsDriverManager takes care of details

* Starting with JDBC4 (part of Java 6), the driver is loaded automatically* Starting with JDBC4 (part of Java 6), the driver is loaded automatically

Page 23: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Statement TypesStatement Types

StatementStatement: SQL is sent to database : SQL is sent to database each timeeach time

PreparedStatementPreparedStatement: compiled version : compiled version of statement is cached and executed more of statement is cached and executed more than oncethan once

CallableStatementCallableStatement: used to call stored : used to call stored proceduresprocedures

Page 24: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

JDBC StatementsJDBC Statements

Statement stmt = conn.createStatement();String cmd = "INSERT INTO Users ('User1', 'Password')";

try { stmt.executeUpdate(cmd);}finally { stmt.close();}

Page 25: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

ResultSetResultSetConnection conn = null;Statement stmt = conn.createStatement();

try { ResultSet rs = stmt.executeQuery("SELECT * FROM PRODUCT");

try { while (rs.next()) { int id = rs.getInt("ITEMID"); double price = rs.getDouble("PRICE"); String desc = rs.getString("DESCRIPTION"); // Do something with data } } finally { rs.close(); } } finally { stmt.close(); }

Page 26: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

ResultSetResultSetStatement stmt = conn.createStatement();

try { ResultSet rs = stmt.executeQuery("SELECT ID,PRICE,DESC FROM PRODUCT"); try { while (rs.next()) { int id = rs.getInt(1); double price = rs.getDouble(2); String desc = rs.getString(3); // Do something with data } } finally { rs.close(); }}finally { stmt.close();}

Page 27: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

hsqldbhsqldb

http://hsqldb.org/http://hsqldb.org/ - 100% Java Database - 100% Java Database

Open-source database we will be using for Open-source database we will be using for labslabs

We will be using the latest version: 2.0.0 We will be using the latest version: 2.0.0 RC 9RC 9

Page 28: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

hsqldb - Installation Instructionshsqldb - Installation Instructions

Download and unzip into a local directory Download and unzip into a local directory (for example C:\java\db\hsqldb)(for example C:\java\db\hsqldb)

Create .cmd file to start hsqldb server C:\Create .cmd file to start hsqldb server C:\java\db\hsqldb\data\StartHSQLDB.cmd)java\db\hsqldb\data\StartHSQLDB.cmd)

cd C:\java\db\hsqldb\datacd C:\java\db\hsqldb\data

java -cp ../lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:mydb --dbname.0 xdbjava -cp ../lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:mydb --dbname.0 xdb

Page 29: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Validate InstallationValidate Installation

Start server, and run Testdb class from Start server, and run Testdb class from documentationdocumentation

Start with Testdb.java (in Week 4 folder on Start with Testdb.java (in Week 4 folder on Website)Website)

Add hsqldb.jar to build pathAdd hsqldb.jar to build path

Page 30: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

hsqldbhsqldbCREATE SCHEMA PUBLIC AUTHORIZATION DBACREATE SCHEMA PUBLIC AUTHORIZATION DBACREATE MEMORY TABLE SAMPLE_TABLE(ID INTEGER GENERATED BY CREATE MEMORY TABLE SAMPLE_TABLE(ID INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,STR_COL DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,STR_COL VARCHAR(256),NUM_COL INTEGER)VARCHAR(256),NUM_COL INTEGER)ALTER TABLE SAMPLE_TABLE ALTER COLUMN ID RESTART WITH 8ALTER TABLE SAMPLE_TABLE ALTER COLUMN ID RESTART WITH 8CREATE USER SA PASSWORD ""CREATE USER SA PASSWORD ""GRANT DBA TO SAGRANT DBA TO SASET WRITE_DELAY 10SET WRITE_DELAY 10SET SCHEMA PUBLICSET SCHEMA PUBLICINSERT INTO SAMPLE_TABLE VALUES(0,'Ford',100)INSERT INTO SAMPLE_TABLE VALUES(0,'Ford',100)INSERT INTO SAMPLE_TABLE VALUES(1,'Toyota',200)INSERT INTO SAMPLE_TABLE VALUES(1,'Toyota',200)INSERT INTO SAMPLE_TABLE VALUES(2,'Honda',300)INSERT INTO SAMPLE_TABLE VALUES(2,'Honda',300)INSERT INTO SAMPLE_TABLE VALUES(3,'GM',400)INSERT INTO SAMPLE_TABLE VALUES(3,'GM',400)INSERT INTO SAMPLE_TABLE VALUES(4,'Ford',100)INSERT INTO SAMPLE_TABLE VALUES(4,'Ford',100)INSERT INTO SAMPLE_TABLE VALUES(5,'Toyota',200)INSERT INTO SAMPLE_TABLE VALUES(5,'Toyota',200)INSERT INTO SAMPLE_TABLE VALUES(6,'Honda',300)INSERT INTO SAMPLE_TABLE VALUES(6,'Honda',300)INSERT INTO SAMPLE_TABLE VALUES(7,'GM',400)INSERT INTO SAMPLE_TABLE VALUES(7,'GM',400)

Page 31: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction

Lab 4-1 Database (Hypersonic) Set UpLab 4-1 Database (Hypersonic) Set Up

Due May 30Due May 30thth!!

Page 32: COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction