Chapter 8 Databases Objectives • Explain the structure of a relational database • Use SQL for creating, maintaining, and accessing relational databases • Use Java/JDBC for accessing relational databases • Explain and apply basic principles of good database design RDBMS • A Relational Database Management System (RDBMS) provides data storage and access for web applications Relation • relation is a mathematical term that refers to an ordered set of values drawn from different domains Ex: a relation on numbers x letters x symbols (55, A, #) Database Structure • A database includes one or more tables – Each table represents one type of entity • Example: Tables in a Library Database Patron Loan (transaction) Recording Book Database Structure • Each table field represents an entity attribute • Each table row represents one entity Car table: Year 1973 1992 2004 row field Make Model Color Volkswagen Jetta Red Ford Aerostar Blue Chevrolet Suburban Black Structured Query Language • SQL is a standard language for creating and maintaining relational databases • SQL statement types: – data definition: create databases and tables – data manipulation: add, modify, delete data – data control: set access permissions Basic SQL Statements • Data definition – CREATE, DROP • Data manipulation – SELECT, INSERT, UPDATE, DELETE • Data control – GRANT, REVOKE CREATE • Create a database or a table CREATE DATABASE ehsl CREATE ehsl.player ( playerNr int PRIMARY KEY, name VARCHAR(30), isCurrent BOOLEAN NOT NULL) Basic SQL Data Types • INTEGER • DECIMAL(T, R) – T=total digits, R=right digits (after '.') • FLOAT • CHAR(N) • VARCHAR(N) • BOOLEAN • DATE • TIME N characters up to N characters DROP • DROP can be used to delete an entire database or a table DROP ehsl DROP ehsl.player SELECT • SELECT retrieves data from a database SELECT field-list FROM database.table WHERE condition ORDER BY field-list – field-list is a comma-separated list of fields from the named table (* means "all fields") – condition is a Boolean condition using field names and/or constants SELECT • Example SELECT * FROM ehsl.player SELECT playerNr, name FROM ehsl.player WHERE isCurrent=TRUE SELECT playerNr, name, status FROM ehsl.player WHERE playerNr >= 90001 ORDER BY status, name INSERT • INSERT adds a new row to a table INSERT INTO ehsl.player VALUES (23752, 'Jane Doe', TRUE) UPDATE • UPDATE changes one or more rows UPDATE database.table SET field-assignment-list WHERE condition UPDATE ehsl.player SET isCurrent=TRUE WHERE playerNr=33256 DELETE • DELETE removes one or more rows from a table DELETE FROM database.table WHERE condition DELETE FROM ehsl.player WHERE playerNr=33523 Warning • UPDATE and DELETE without a WHERE clause will affect all rows! UPDATE ehsl.player SET isCurrent=true DELETE FROM ehsl.player Change all rows! Delete all rows! GRANT • GRANT can be used to give access permissions to users GRANT ALL PRIVILEGES ON database.table TO user-name – user-name is formatted as user@host, for example 'jonesac'@'localhost' REVOKE • REVOKE can be used to eliminate access permissions REVOKE ALL PRIVILEGES on database.table FROM user-name REVOKE ALL PRIVILEGES on ehsl.player FROM 'jonesac'@'localhost' Create User • The CREATE command can also be used to create new users CREATE USER user-name IDENTIFIED BY password CREATE USER 'jonesac'@'localhost' IDENTIFIEC BY 'abc123#' JDBC • Java Database Connectivity (JDBC) is a Java API that allows Java programs to interact with relational database management systems • Interaction also requires a database driver, which translates JDBC commands to procedure calls on the RDBMS Application Program RDBMS Driver JDBC JDBC – Load Driver • The first step is to load the database driver – Usually provided by the RDBMS vendor String driverClassName = "com.mysql.jdbc.Driver"; try { Class.forName(driverClassName); } catch (ClassNotFoundException cnfe) { …. } JDBC – Execute Query (1/2) • To execute an SQL Query: String query = "..."; Vector<String> colNames = new Vector<String>, result = new Vector<String>; try { Connection con = DriverManager.getConnection( dbUrl, dbUserId, dbPassword); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(query); ResultSetMetaData md = rs.getMetaData(); JDBC – Execute Query (2/2) • To execute an SQL Query: // get column names for (int i = 1; i <= md.getColumnCount(); i++) { colNames.addColumnName(md.getColumnName(i)); } access the next row of the table // get field values while (rs.next()) { for (int i = 1; i<=md.getColumnCount(); i++) { result.addFieldValue(rs.getString(i)); } } access the next field of the row con.close(); } catch (SQLException s) { ... } JDBC – Execute Command • To execute an SQL command: int result = 0; String command = "..."; try { con = DriverManager.getConnection( dbUrl, dbUserId, dbPassword); stmt = con.createStatement(); result = stmt.executeUpdate(command); con.close(); } catch (SQLException s) { ... result = number of rows affected } (inserted, modified, or deleted) JDBC Design • An effective design for database access: – JSP: – Java Servlet: – Java Bean: JSP create user interface Java Servlet process / prepare data user interface presentation application logic database access (JDBC) Java Bean access RDBMS using JDBC RDBMS dependency Database Design Principles 1. Each field should contain a single value 2. Repeated fields with empty values should be made a separate table 3. Each table should represent only one entity Example: Registration • WRONG: multiple valued field • Better: empty fields Example: Registration • Better still: multiple entities: class registration / class name Example: Registration • RIGHT: Review • Relational Database / RDBMS • SQL – Data Definition – Data Manipulation – Data Control • JDBC – Database Driver – Query Execution – Command Execution • Database Design Principles