COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb...
-
Upload
linda-tucker -
Category
Documents
-
view
236 -
download
0
Transcript of COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb...
COMP 321COMP 321
Week 4Week 4
OverviewOverview
NormalizationNormalization
Entity-Relationship DiagramsEntity-Relationship Diagrams
SQLSQL
JDBC/JDBC DriversJDBC/JDBC Drivers
hsqldbhsqldb
Lab 4-1 IntroductionLab 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
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))
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))
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))
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))
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.
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.
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
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
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
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
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
JDBCJDBC
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
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
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
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
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
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)
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
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
JDBC StatementsJDBC Statements
Statement stmt = conn.createStatement();String cmd = "INSERT INTO Users ('User1', 'Password')";
try { stmt.executeUpdate(cmd);}finally { stmt.close();}
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(); }
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();}
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
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
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
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)
Lab 4-1 Database (Hypersonic) Set UpLab 4-1 Database (Hypersonic) Set Up
Due May 30Due May 30thth!!